code
stringlengths
2.5k
150k
kind
stringclasses
1 value
cpp std::iswprint std::iswprint ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswprint( std::wint_t ch ); ``` | | | Checks if the given wide character can be printed, i.e. it is either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`), a punctuation character(`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`), space or any printable 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 can be printed, zero otherwise. ### Notes [ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX print category. ### Example ``` #include <iostream> #include <cwctype> #include <clocale> int main() { wchar_t c = L'\u2002'; // en-space std::setlocale(LC_ALL, "en_US.utf8"); std::cout << std::boolalpha << std::hex << std::showbase << "in Unicode locale,\n" << "iswprint('" << c << "') = " << (bool)std::iswprint(c) << '\n'; c = L'\u0082'; // break permitted std::cout << "iswprint('" << c << "') = " << (bool)std::iswprint(c) << '\n'; } ``` Output: ``` in Unicode locale, iswprint('0x2002') = true iswprint('0x82') = false ``` ### See also | | | | --- | --- | | [isprint(std::locale)](../../locale/isprint "cpp/locale/isprint") | checks if a character is classified as printable by a locale (function template) | | [isprint](../byte/isprint "cpp/string/byte/isprint") | checks if a character is a printing character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswprint "c/string/wide/iswprint") for `iswprint` | | ASCII values | characters | [`iscntrl`](../byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "cpp/string/byte/isprint") **`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`](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::wcspbrk std::wcspbrk ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` const wchar_t* wcspbrk( const wchar_t* dest, const wchar_t* str ); ``` | | | | ``` wchar_t* wcspbrk( wchar_t* dest, const wchar_t* str ); ``` | | | Finds the first character in wide string pointed to by `dest`, that is also in wide string pointed to by `str`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated wide string to be analyzed | | src | - | pointer to the null-terminated wide string that contains the characters to search for | ### Return value Pointer to the first character in `dest`, that is also in `str`, or a null pointer if no such character exists. ### Notes The name stands for "wide character string pointer break", because it returns a pointer to the first of the separator ("break") characters. ### Example ``` #include <iostream> #include <cwchar> #include <iomanip> int main() { const wchar_t* str = L"Hello world, friend of mine!"; const wchar_t* sep = L" ,!"; unsigned int cnt = 0; do { str = std::wcspbrk(str, sep); // find separator std::wcout << std::quoted(str) << L'\n'; if (str) str += std::wcsspn(str, sep); // skip separator ++cnt; // increment word count } while (str && *str); std::wcout << L"There are " << cnt << L" words\n"; } ``` Output: ``` " world, friend of mine!" ", friend of mine!" " of mine!" " mine!" "!" There are 5 words ``` ### See also | | | | --- | --- | | [wcscspn](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) | | [wcschr](wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) | | [strpbrk](../byte/strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcspbrk "c/string/wide/wcspbrk") for `wcspbrk` | cpp std::wcsncmp std::wcsncmp ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int wcsncmp( const wchar_t* lhs, const wchar_t* rhs, std::size_t count ); ``` | | | Compares at most `count` wide characters of two null-terminated wide strings. 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 strings being compared. The behavior is undefined if `lhs` or `rhs` are not pointers to null-terminated strings. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pointers to the null-terminated wide strings to compare | | count | - | maximum number of characters to compare | ### Return value Negative value if `lhs` appears before `rhs` in lexicographical order. Zero if `lhs` and `rhs` compare equal. Positive value if `lhs` appears after `rhs` in lexicographical order. ### Example ``` #include <iostream> #include <cwchar> #include <clocale> #include <locale> void demo(const wchar_t* lhs, const wchar_t* rhs, int sz) { int rc = std::wcsncmp(lhs, rhs, sz); if(rc == 0) std::wcout << "First " << sz << " characters of [" << lhs << "] equal [" << rhs << "]\n"; else if(rc < 0) std::wcout << "First " << sz << " characters of [" << lhs << "] precede [" << rhs << "]\n"; else if(rc > 0) std::wcout << "First " << sz << " characters of [" << lhs << "] follow [" << rhs << "]\n"; } int main() { const wchar_t str1[] = L"안녕하세요"; const wchar_t str2[] = L"안녕히 가십시오"; std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); demo(str1, str2, 5); demo(str2, str1, 8); demo(str1, str2, 2); } ``` Output: ``` First 5 characters of [안녕하세요] precede [안녕히 가십시오] First 8 characters of [안녕히 가십시오] follow [안녕하세요] First 2 characters of [안녕하세요] equal [안녕히 가십시오] ``` ### See also | | | | --- | --- | | [strncmp](../byte/strncmp "cpp/string/byte/strncmp") | compares a certain number of characters from two strings (function) | | [wcscmp](wcscmp "cpp/string/wide/wcscmp") | compares two wide strings (function) | | [wmemcmp](wmemcmp "cpp/string/wide/wmemcmp") | compares a certain amount of wide characters from two arrays (function) | | [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/wcsncmp "c/string/wide/wcsncmp") for `wcsncmp` | cpp std::iswblank std::iswblank ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswblank( std::wint_t ch ); ``` | | (since C++11) | Checks if the given wide character is classified as blank character (that is, a whitespace character used to separate words in a sentence) by the current C locale. In the default C locale, only space (`0x20`) and horizontal tab (`0x09`) are blank characters. 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 blank character, zero otherwise. ### Notes [ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) defines POSIX blank characters as Unicode characters U+0009, U+0020, U+1680, U+180E, U+2000..U+2006, U+2008, U+200A, U+205F, and U+3000. ### Example ``` #include <iostream> #include <cwctype> #include <clocale> int main() { wchar_t c = L'\u3000'; // Ideographic space (' ') std::cout << std::hex << std::showbase << std::boolalpha; std::cout << "in the default locale, iswblank(" << (std::wint_t)c << ") = " << (bool)std::iswblank(c) << '\n'; std::setlocale(LC_ALL, "en_US.utf8"); std::cout << "in Unicode locale, iswblank(" << (std::wint_t)c << ") = " << (bool)std::iswblank(c) << '\n'; } ``` Output: ``` in the default locale, iswblank(0x3000) = false in Unicode locale, iswblank(0x3000) = true ``` ### See also | | | | --- | --- | | [isblank(std::locale)](../../locale/isblank "cpp/locale/isblank") (C++11) | checks if a character is classified as a blank character by a locale (function template) | | [isblank](../byte/isblank "cpp/string/byte/isblank") (C++11) | checks if a character is a blank character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswblank "c/string/wide/iswblank") for `iswblank` | | 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`**. | [`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`](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::wctrans std::wctrans ============ | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` std::wctrans_t wctrans( const char* str ); ``` | | | Constructs a value of type `std::wctrans_t` that describes a LC\_CTYPE category of wide character mapping. It may be one of the standard mappings, or a locale-specific mapping, such as `"tojhira"` or `"tojkata"`. ### Parameters | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | str | - | C string holding the name of the desired mapping. The following values of `str` are supported in all C locales: | Value of `str` | Effect | | --- | --- | | `"toupper"` | identifies the mapping used by `towupper` | | `"tolower"` | identifies the mapping used by `towlower` | | ### Return value `std::wctrans_t` object suitable for use with `[std::towctrans](towctrans "cpp/string/wide/towctrans")` to map wide characters according to the named mapping of the current C locale or zero if `str` does not name a mapping supported by the current C locale. ### See also | | | | --- | --- | | [towctrans](towctrans "cpp/string/wide/towctrans") | performs character mapping according to the specified LC\_CTYPE mapping category (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wctrans "c/string/wide/wctrans") for `wctrans` | cpp std::iswdigit std::iswdigit ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswdigit( wint_t ch ); ``` | | | Checks if the given wide character corresponds (if narrowed) to one of the ten decimal digit characters `0123456789`. 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 numeric character, zero otherwise. ### Notes `std::iswdigit` and `[std::iswxdigit](iswxdigit "cpp/string/wide/iswxdigit")` are the only standard wide character classification functions that are not affected by the currently installed C locale. ### Example Some locales offer additional character classes that detect non-ASCII digits. ``` #include <iostream> #include <cwctype> #include <clocale> void test(wchar_t a3, wchar_t u3, wchar_t j3) { std::wcout << std::boolalpha << " '" << a3 << "' '" << u3 << "' '" << j3 << "'\n" << "iswdigit " << (bool)std::iswdigit(a3) << " " << (bool)std::iswdigit(u3) << " " << (bool)std::iswdigit(j3) << '\n' << "jdigit: " << (bool)std::iswctype(a3, std::wctype("jdigit")) << ' ' << (bool)std::iswctype(u3, std::wctype("jdigit")) << ' ' << (bool)std::iswctype(j3, std::wctype("jdigit")) << '\n'; } int main() { wchar_t a3 = L'3'; // the ASCII digit 3 wchar_t u3 = L'三'; // the CJK numeral 3 wchar_t j3 = L'3'; // the fullwidth digit 3 std::setlocale(LC_ALL, "en_US.utf8"); std::wcout << "In american locale:\n"; test(a3, u3, j3); std::wcout << "\nIn japanese locale:\n"; std::setlocale(LC_ALL, "ja_JP.utf8"); test(a3, u3, j3); } ``` Output: ``` In american locale: '3' '三' '3' iswdigit true false false jdigit: false false false In japanese locale: '3' '三' '3' iswdigit true false false jdigit: false false true ``` ### See also | | | | --- | --- | | [isdigit(std::locale)](../../locale/isdigit "cpp/locale/isdigit") | checks if a character is classified as a digit by a locale (function template) | | [isdigit](../byte/isdigit "cpp/string/byte/isdigit") | checks if a character is a digit (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswdigit "c/string/wide/iswdigit") for `iswdigit` | | 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`](iswlower "cpp/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "cpp/string/byte/isdigit") **`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::wcsspn std::wcsspn =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` size_t wcsspn( const wchar_t* dest, const wchar_t* src ); ``` | | | Returns the length of the maximum initial segment of the wide string pointed to by `dest`, that consists of only the characters found in wide string pointed to by `src`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated wide string to be analyzed | | src | - | pointer to the null-terminated wide string that contains the characters to search for | ### Return value The length of the maximum initial segment that contains only characters from wide string pointed to by `src`. ### Example ``` #include <cwchar> #include <iostream> #include <locale> int main() { wchar_t dest[] = L"白猫 黑狗 甲虫"; const wchar_t src[] = L" 狗猫 白黑 "; const std::size_t len = std::wcsspn(dest, src); dest[len] = L'\0'; // terminates the segment to print it out std::wcout.imbue(std::locale("en_US.utf8")); std::wcout << L"The length of maximum initial segment is " << len << L".\n"; std::wcout << L"The segment is \"" << dest << L"\".\n"; } ``` Possible output: ``` The length of maximum initial segment is 6. The segment is "白猫 黑狗 ". ``` ### See also | | | | --- | --- | | [wcscspn](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](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/wcsspn "c/string/wide/wcsspn") for `wcsspn` | cpp std::iswupper std::iswupper ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswupper( std::wint_t ch ); ``` | | | Checks if the given wide character is an uppercase letter, i.e. one of `ABCDEFGHIJKLMNOPQRSTUVWXYZ` or any uppercase 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 uppercase 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 upper category. ### Example ``` #include <iostream> #include <cwctype> #include <clocale> int main() { wchar_t c = L'\u053d'; // Armenian capital letter xeh ('Խ') std::cout << std::hex << std::showbase << std::boolalpha; std::cout << "in the default locale, iswupper(" << (std::wint_t)c << ") = " << (bool)std::iswupper(c) << '\n'; std::setlocale(LC_ALL, "en_US.utf8"); std::cout << "in Unicode locale, iswupper(" << (std::wint_t)c << ") = " << (bool)std::iswupper(c) << '\n'; } ``` Output: ``` in the default locale, iswupper(0x53d) = false in Unicode locale, iswupper(0x53d) = true ``` ### See also | | | | --- | --- | | [isupper(std::locale)](../../locale/isupper "cpp/locale/isupper") | checks if a character is classified as uppercase by a locale (function template) | | [isupper](../byte/isupper "cpp/string/byte/isupper") | checks if a character is an uppercase character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswupper "c/string/wide/iswupper") for `iswupper` | | 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`**. | [`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::wcscspn std::wcscspn ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t wcscspn( const wchar_t* dest, const wchar_t* src ); ``` | | | Returns the length of the maximum initial segment of the wide string pointed to by `dest`, that consists of only the characters *not* found in wide string pointed to by `src`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated wide string to be analyzed | | src | - | pointer to the null-terminated wide string that contains the characters to search for | ### Return value The length of the maximum initial segment that contains only characters not found in the character string pointed to by `src`. ### Example ``` #include <cwchar> #include <iostream> #include <locale> int main() { wchar_t dest[] = L"白猫 黑狗 甲虫"; // └───┐ const wchar_t *src = L"甲虫,黑狗"; const std::size_t len = std::wcscspn(dest, src); dest[len] = L'\0'; // terminates the segment to print it out std::wcout.imbue(std::locale("en_US.utf8")); std::wcout << L"The length of maximum initial segment is " << len << L".\n"; std::wcout << L"The segment is \"" << dest << L"\".\n"; } ``` Possible output: ``` The length of maximum initial segment is 3. The segment is "白猫 ". ``` ### See also | | | | --- | --- | | [wcsspn](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) | | [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/wcscspn "c/string/wide/wcscspn") for `wcscspn` | cpp std::iswcntrl std::iswcntrl ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswcntrl( std::wint_t ch ); ``` | | | Checks if the given wide character is a control character, i.e. codes `0x00-0x1F` and `0x7F` and any control characters 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 control character, zero otherwise. ### Notes ISO 30112 defines POSIX control characters as Unicode characters U+0000..U+001F, U+007F..U+009F, U+2028, and U+2029 (Unicode classes Cc, Zl, and Zp). ### Example ``` #include <iostream> #include <cwctype> #include <clocale> int main() { wchar_t c = L'\u2028'; // the Unicode character "line separator" std::cout << std::hex << std::showbase << std::boolalpha; std::cout << "in the default locale, iswcntrl(" << (std::wint_t)c << ") = " << (bool)std::iswcntrl(c) << '\n'; std::setlocale(LC_ALL, "en_US.utf8"); std::cout << "in Unicode locale, iswcntrl(" << (std::wint_t)c << ") = " << (bool)std::iswcntrl(c) << '\n'; } ``` Output: ``` in the default locale, iswcntrl(0x2028) = false in Unicode locale, iswcntrl(0x2028) = true ``` ### See also | | | | --- | --- | | [iscntrl(std::locale)](../../locale/iscntrl "cpp/locale/iscntrl") | checks if a character is classified as a control character by a locale (function template) | | [iscntrl](../byte/iscntrl "cpp/string/byte/iscntrl") | checks if a character is a control character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswcntrl "c/string/wide/iswcntrl") for `iswcntrl` | | ASCII values | characters | [`iscntrl`](../byte/iscntrl "cpp/string/byte/iscntrl") **`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`](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::iswpunct std::iswpunct ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswpunct( std::wint_t ch ); ``` | | | Checks if the given wide character is a punctuation character, i.e. it is one of `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` or any punctuation 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 punctuation 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 punct category. ### Example ``` #include <iostream> #include <cwctype> #include <clocale> int main() { wchar_t c = L'\u2051'; // Two asterisks ('⁑') std::cout << std::hex << std::showbase << std::boolalpha; std::cout << "in the default locale, iswpunct(" << (std::wint_t)c << ") = " << (bool)std::iswpunct(c) << '\n'; std::setlocale(LC_ALL, "en_US.utf8"); std::cout << "in Unicode locale, iswpunct(" << (std::wint_t)c << ") = " << (bool)std::iswpunct(c) << '\n'; } ``` Output: ``` in the default locale, iswpunct(0x2051) = false in Unicode locale, iswpunct(0x2051) = true ``` ### See also | | | | --- | --- | | [ispunct(std::locale)](../../locale/ispunct "cpp/locale/ispunct") | checks if a character is classified as punctuation by a locale (function template) | | [ispunct](../byte/ispunct "cpp/string/byte/ispunct") | checks if a character is a punctuation character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswpunct "c/string/wide/iswpunct") for `iswpunct` | | 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`**. | [`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`** |
programming_docs
cpp std::wcstol, std::wcstoll std::wcstol, std::wcstoll ========================= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` long wcstol( const wchar_t* str, wchar_t** str_end, int base ); ``` | | | | ``` long long wcstoll( const wchar_t* str, wchar_t** str_end, int base ); ``` | | (since C++11) | Interprets an 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`) integer number representation and converts them to an integer value. The valid 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. 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 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 `[LONG\_MAX](../../types/climits "cpp/types/climits")`, `[LONG\_MIN](../../types/climits "cpp/types/climits")`, `[LLONG\_MAX](../../types/climits "cpp/types/climits")` or `[LLONG\_MIN](../../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 (long i = std::wcstol(p, &end, 10); p != end; i = std::wcstol(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 9223372036854775807 ' 30' -> 30 ' -40' -> -40 ``` ### See also | | | | --- | --- | | [strtolstrtoll](../byte/strtol "cpp/string/byte/strtol") (C++11) | converts a byte string to an integer value (function) | | [wcstoulwcstoull](wcstoul "cpp/string/wide/wcstoul") | converts a wide string to an unsigned integer value (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcstol "c/string/wide/wcstol") for `wcstol, wcstoll` | cpp std::wcscmp std::wcscmp =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int wcscmp( const wchar_t* lhs, const wchar_t* rhs ); ``` | | | Compares two null-terminated wide strings 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 strings being compared. The behavior is undefined if `lhs` or `rhs` are not pointers to null-terminated wide strings. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pointers to the null-terminated wide strings to compare | ### Return value Negative value if `lhs` appears before `rhs` in lexicographical order. Zero if `lhs` and `rhs` compare equal. Positive value if `lhs` appears after `rhs` in lexicographical order. ### Notes This function is not locale-sensitive, unlike `[std::wcscoll](wcscoll "cpp/string/wide/wcscoll")`, and the order may not be meaningful when characters from different Unicode blocks are used together or when the order of code units does not match collation order. ### Example ``` #include <vector> #include <cwchar> #include <algorithm> #include <iostream> int main() { std::vector<const wchar_t*> leaders{L"Ленин", L"Сталин", L"Маленков", L"Хрущёв", L"Брежнев", L"Андропов", L"Черненко", L"Горбачёв"}; std::sort(leaders.begin(), leaders.end(), [](auto strA, auto strB) { return std::wcscmp(strA, strB) < 0; }); std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); for (auto leader : leaders) std::wcout << leader << '\n'; } ``` Possible output: ``` Андропов Брежнев Горбачёв Ленин Маленков Сталин Хрущёв Черненко ``` ### See also | | | | --- | --- | | [wcsncmp](wcsncmp "cpp/string/wide/wcsncmp") | compares a certain amount of characters from two wide strings (function) | | [wmemcmp](wmemcmp "cpp/string/wide/wmemcmp") | compares a certain amount of wide characters from two arrays (function) | | [strcmp](../byte/strcmp "cpp/string/byte/strcmp") | compares two strings (function) | | [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/wcscmp "c/string/wide/wcscmp") for `wcscmp` | cpp std::towctrans std::towctrans ============== | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` std::wint_t towctrans( std::wint_t wc, std::wctrans_t desc ); ``` | | | Maps the wide character `wc` using the current C locale's LC\_CTYPE mapping category identified by `desc`. 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 | - | the wide character to map | | desc | - | the LC\_CTYPE mapping, obtained from a call to `[std::wctrans](wctrans "cpp/string/wide/wctrans")` | ### Return value The mapped value of `ch` using the mapping identified by `desc` in LC\_CTYPE facet of the current C locale. ### Example The following example demonstrates katakana to hiragana character mapping. ``` #include <clocale> #include <cwctype> #include <iostream> #include <algorithm> std::wstring tohira(std::wstring str) { std::transform(str.begin(), str.end(), str.begin(), [](wchar_t c) { return std::towctrans(c, std::wctrans("tojhira")); }); return str; } int main() { std::setlocale(LC_ALL, "ja_JP.UTF-8"); std::wstring kana = L"ヒラガナ"; std::wcout << "katakana characters " << kana << " are " << tohira(kana) << " in hiragana\n"; } ``` Output: ``` katakana characters ヒラガナ are ひらがな in hiragana ``` ### See also | | | | --- | --- | | [wctrans](wctrans "cpp/string/wide/wctrans") | looks up a character mapping category in the current C locale (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/towctrans "c/string/wide/towctrans") for `towctrans` | cpp std::wcslen std::wcslen =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t wcslen( const wchar_t* str ); ``` | | | Returns the length of a wide string, that is the number of non-null wide characters that precede the terminating null wide character. The behavior is undefined if there is no null character in the wide character array pointed to by `str`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated wide string to be examined | ### Return value The length of the null-terminated wide string `str`. ### Possible implementation | | | --- | | ``` std::size_t wcslen(const wchar_t* start) { // NB: no nullptr checking! const wchar_t* end = start; for( ; *end != L'\0'; ++end) ; return end - start; } ``` | ### Example ``` #include <iostream> #include <cwchar> #include <clocale> int main() { const wchar_t* str = L"爆ぜろリアル!弾けろシナプス!パニッシュメントディス、ワールド!"; std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); std::wcout << "The length of \"" << str << "\" is " << std::wcslen(str) << '\n'; } ``` Output: ``` The length of "爆ぜろリアル!弾けろシナプス!パニッシュメントディス、ワールド!" is 32 ``` ### See also | | | | --- | --- | | [strlen](../byte/strlen "cpp/string/byte/strlen") | returns the length of a given string (function) | | [mblen](../multibyte/mblen "cpp/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcslen "c/string/wide/wcslen") for `wcslen` | cpp std::wmemchr std::wmemchr ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` const wchar_t* wmemchr( const wchar_t* ptr, wchar_t ch, std::size_t count ); ``` | | | | ``` wchar_t* wmemchr( wchar_t* ptr, wchar_t ch, std::size_t count ); ``` | | | Locates the first occurrence of wide character `ch` in the initial `count` wide characters of the wide character array pointed to by `ptr`. If `count` is zero, the function returns a null pointer. ### Parameters | | | | | --- | --- | --- | | ptr | - | pointer to the wide character array to be examined | | ch | - | wide character to search for | | count | - | number of wide characters to examine | ### Return value Pointer to the location of the wide character, or a null pointer if no such character is found. ### Example ``` #include <iostream> #include <cwchar> #include <clocale> #include <locale> int main() { const wchar_t str[] = L"诺不轻信,故人不负我\0诺不轻许,故我不负人。"; wchar_t target = L'许'; const std::size_t sz = sizeof str / sizeof *str; if (const wchar_t* result = std::wmemchr(str, target, sz)) { std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); std::wcout << "Found '" << target << "' at position " << result - str << "\n"; } } ``` Possible output: ``` Found '许' at position 14 ``` ### See also | | | | --- | --- | | [memchr](../byte/memchr "cpp/string/byte/memchr") | searches an array for the first occurrence of a character (function) | | [strchr](../byte/strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) | | [wcschr](wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) | | [findfind\_iffind\_if\_not](../../algorithm/find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wmemchr "c/string/wide/wmemchr") for `wmemchr` | cpp std::towlower std::towlower ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` std::wint_t towlower( std::wint_t ch ); ``` | | | Converts the given wide character to lowercase, 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 Lowercase version of `ch` or unmodified `ch` if no lowercase version is listed in the current C locale. ### Notes Only 1:1 character mapping can be performed by this function, e.g. the Greek uppercase letter 'Σ' has two lowercase forms, depending on the position in a word: 'σ' and 'ς'. A call to `std::towlower` cannot be used to obtain the correct lowercase form in this case. [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 ``` #include <iostream> #include <cwctype> #include <clocale> int main() { wchar_t c = L'\u0190'; // Latin capital open E ('Ɛ') std::cout << std::hex << std::showbase; std::cout << "in the default locale, towlower(" << (std::wint_t)c << ") = " << std::towlower(c) << '\n'; std::setlocale(LC_ALL, "en_US.utf8"); std::cout << "in Unicode locale, towlower(" << (std::wint_t)c << ") = " << std::towlower(c) << '\n'; } ``` Output: ``` in the default locale, towlower(0x190) = 0x190 in Unicode locale, towlower(0x190) = 0x25b ``` ### See also | | | | --- | --- | | [towupper](towupper "cpp/string/wide/towupper") | converts a wide character to uppercase (function) | | [tolower(std::locale)](../../locale/tolower "cpp/locale/tolower") | converts a character to lowercase using the ctype facet of a locale (function template) | | [tolower](../byte/tolower "cpp/string/byte/tolower") | converts a character to lowercase (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/towlower "c/string/wide/towlower") for `towlower` | cpp std::wcsrchr std::wcsrchr ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` const wchar_t* wcsrchr( const wchar_t* str, wchar_t ch ); ``` | | | | ``` wchar_t* wcsrchr( wchar_t* str, wchar_t ch ); ``` | | | Finds the last 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::wcsrchr(arr, L'猫'); const wchar_t* dog = std::wcsrchr(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 4 The character 犬 not found ``` ### See also | | | | --- | --- | | [wcschr](wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) | | [strrchr](../byte/strrchr "cpp/string/byte/strrchr") | finds the last occurrence of a character (function) | | [rfind](../basic_string/rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcsrchr "c/string/wide/wcsrchr") for `wcsrchr` | cpp std::wcscat std::wcscat =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wchar_t *wcscat( wchar_t *dest, const wchar_t *src ); ``` | | | Appends a copy of the wide string pointed to by `src` to the end of the wide string pointed to by `dest`. The wide character `src[0]` replaces the null terminator at the end of `dest`. The resulting wide string is null-terminated. 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 | ### Return value Returns a copy of `dest`. ### Example ``` #include <iostream> #include <cwchar> #include <clocale> int main(void) { wchar_t str[50] = L"Земля, прощай."; std::wcscat(str, L" "); std::wcscat(str, L"В добрый путь."); std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); std::wcout << str << '\n'; } ``` Possible output: ``` Земля, прощай. В добрый путь. ``` ### See also | | | | --- | --- | | [wcsncat](wcsncat "cpp/string/wide/wcsncat") | appends a certain amount of wide characters from one wide string to another (function) | | [strcat](../byte/strcat "cpp/string/byte/strcat") | concatenates 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/wcscat "c/string/wide/wcscat") for `wcscat` | cpp std::wcstok std::wcstok =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wchar_t* wcstok( wchar_t* str, const wchar_t* delim, wchar_t ** ptr); ``` | | | Finds the next token in a null-terminated wide string pointed to by `str`. The separator characters are identified by null-terminated wide string pointed to by `delim`. This function is designed to be called multiples times to obtain successive tokens from the same string. * If `str != nullptr`, the call is treated as the first call to `std::wcstok` for this particular wide string. The function searches for the first wide character which is *not* contained in `delim`. * If no such wide character was found, there are no tokens in `str` at all, and the function returns a null pointer. * If such wide character was found, it is the *beginning of the token*. The function then searches from that point on for the first wide character that *is* contained in `delim`. + If no such wide character was found, `str` has only one token, and future calls to `std::wcstok` will return a null pointer + If such wide character was found, it is *replaced* by the null wide character `L'\0'` and the parser state (typically a pointer to the following wide character) is stored in the user-provided location `*ptr`. * The function then returns the pointer to the beginning of the token * If `str == nullptr`, the call is treated as a subsequent calls to `std::wcstok`: the function continues from where it left in previous invocation with the same `*ptr`. The behavior is the same as if the pointer to the wide character that follows the last detected token is passed as `str`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated wide string to tokenize | | delim | - | pointer to the null-terminated wide string identifying delimiters | | ptr | - | pointer to an object of type `wchar_t*`, which is used by wcstok to store its internal state | ### Return value Pointer to the beginning of the next token or null pointer if there are no more tokens. ### Note This function is destructive: it writes the `L'\0'` characters in the elements of the string `str`. In particular, a wide string literal cannot be used as the first argument of `std::wcstok`. Unlike `[std::strtok](../byte/strtok "cpp/string/byte/strtok")`, this function does not update static storage: it stores the parser state in the user-provided location. Unlike most other tokenizers, the delimiters in `std::wcstok` can be different for each subsequent token, and can even depend on the contents of the previous tokens. ### Example ``` #include <cwchar> #include <iostream> int main() { wchar_t input[100] = L"A bird came down the walk"; wchar_t* buffer; wchar_t* token = std::wcstok(input, L" ", &buffer); while (token) { std::wcout << token << '\n'; token = std::wcstok(nullptr, L" ", &buffer); } } ``` Output: ``` A bird came down the walk ``` ### See also | | | | --- | --- | | [strtok](../byte/strtok "cpp/string/byte/strtok") | finds the next token in a byte string (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcstok "c/string/wide/wcstok") for `wcstok` |
programming_docs
cpp std::iswxdigit std::iswxdigit ============== | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswxdigit( wint_t ch ); ``` | | | Checks if the given wide character corresponds (if narrowed) to a hexadecimal numeric character, i.e. one of `0123456789abcdefABCDEF`. 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 hexadecimal numeric character, zero otherwise. ### Notes `[std::iswdigit](iswdigit "cpp/string/wide/iswdigit")` and `std::iswxdigit` are the only standard wide character classification functions that are not affected by the currently installed C locale. ### See also | | | | --- | --- | | [isxdigit(std::locale)](../../locale/isxdigit "cpp/locale/isxdigit") | checks if a character is classified as a hexadecimal digit by a locale (function template) | | [isxdigit](../byte/isxdigit "cpp/string/byte/isxdigit") | checks if a character is a hexadecimal character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswxdigit "c/string/wide/iswxdigit") for `iswxdigit` | | 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`](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`**. | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 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::wcsncpy std::wcsncpy ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wchar_t *wcsncpy( wchar_t *dest, const wchar_t *src, std::size_t count ); ``` | | | Copies at most `count` characters of the wide string pointed to by `src` (including the terminating null wide character) to wide character array pointed to by `dest`. If `count` is reached before the entire string `src` was copied, the resulting wide character array is not null-terminated. If, after copying the terminating null wide character from `src`, `count` is not reached, additional null wide characters are written to `dest` until the total of `count` characters have been written. If the strings overlap, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the wide character array to copy to | | src | - | pointer to the wide string to copy from | | count | - | maximum number of wide characters to copy | ### Return value `dest`. ### Notes In typical usage, `count` is the size of the destination array. ### Example ``` #include <iostream> #include <cwchar> int main() { const wchar_t src[] = L"hi"; wchar_t dest[6] = {L'a', L'b', L'c', L'd', L'e', L'f'}; std::wcsncpy(dest, src, 5); // this will copy 'hi' and repeat \0 three times std::wcout << "The contents of dest are: "; for(const wchar_t c : dest) { if(c) std::wcout << c << ' '; else std::wcout << "\\0" << ' '; } std::wcout << '\n'; } ``` Output: ``` The contents of dest are: h i \0 \0 \0 f ``` ### See also | | | | --- | --- | | [wcscpy](wcscpy "cpp/string/wide/wcscpy") | copies one wide string to another (function) | | [wmemcpy](wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) | | [strncpy](../byte/strncpy "cpp/string/byte/strncpy") | copies a certain amount of characters from one string to another (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcsncpy "c/string/wide/wcsncpy") for `wcsncpy` | cpp std::wcstof, std::wcstod, std::wcstold std::wcstof, std::wcstod, std::wcstold ====================================== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` float wcstof( const wchar_t* str, wchar_t** str_end ); ``` | | (since C++11) | | ``` double wcstod( const wchar_t* str, wchar_t** str_end ); ``` | | | | ``` long double wcstold( const wchar_t* str, wchar_t** str_end ); ``` | | (since C++11) | Interprets a floating point value in a wide string pointed to by `str`. Function discards any whitespace characters (as determined by `[std::iswspace](http://en.cppreference.com/w/cpp/string/wide/iswspace)()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following: * decimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10) | | | | --- | --- | | * hexadecimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + `0x` or `0X` + nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2) * infinity expression. It consists of the following parts: + (optional) plus or minus sign + `INF` or `INFINITY` ignoring case * not-a-number expression. It consists of the following parts: + (optional) plus or minus sign + `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value. | (since C++11) | * any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "cpp/locale/setlocale") 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. | ### Return value Floating point 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 `[HUGE\_VAL](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")`, `[HUGE\_VALF](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` or `[HUGE\_VALL](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` is returned. If no conversion can be performed, `​0​` is returned. ### Example ``` #include <iostream> #include <string> #include <cerrno> #include <cwchar> #include <clocale> int main() { const wchar_t* p = L"111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz"; wchar_t* end; std::wcout << "Parsing L\"" << p << "\":\n"; for (double f = std::wcstod(p, &end); p != end; f = std::wcstod(p, &end)) { std::wcout << " '" << std::wstring(p, end-p) << "' -> "; p = end; if (errno == ERANGE){ std::wcout << "range error, got "; errno = 0; } std::wcout << f << '\n'; } if (std::setlocale(LC_NUMERIC, "de_DE.utf8")) { std::wcout << L"With de_DE.utf8 locale:\n"; std::wcout << L" '123.45' -> " << std::wcstod(L"123.45", 0) << L'\n'; std::wcout << L" '123,45' -> " << std::wcstod(L"123,45", 0) << L'\n'; } } ``` Output: ``` Parsing L"111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz": '111.11' -> 111.11 ' -2.22' -> -2.22 ' 0X1.BC70A3D70A3D7P+6' -> 111.11 ' -Inf' -> -inf ' 1.18973e+4932' -> range error, got inf With de_DE.utf8 locale: '123.45' -> 123 '123,45' -> 123.45 ``` ### See also | | | | --- | --- | | [strtofstrtodstrtold](../byte/strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcstof "c/string/wide/wcstof") for `wcstof` | cpp std::wcstoimax, std::wcstoumax std::wcstoimax, std::wcstoumax ============================== | Defined in header `[<cinttypes>](../../header/cinttypes "cpp/header/cinttypes")` | | | | --- | --- | --- | | ``` std::intmax_t wcstoimax( const wchar_t* nptr, wchar_t** endptr, int base ); ``` | | (since C++11) | | ``` std::uintmax_t wcstoumax( const wchar_t* nptr, wchar_t** endptr, int base ); ``` | | (since C++11) | Interprets an unsigned integer value in a wide string pointed to by `nptr`. 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 `endptr` to point to the wide character past the last character interpreted. If `endptr` is a null pointer, it is ignored. ### Parameters | | | | | --- | --- | --- | | nptr | - | pointer to the null-terminated wide string to be interpreted | | endptr | - | 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 `[INTMAX\_MAX](../../types/integer "cpp/types/integer")`, `[INTMAX\_MIN](../../types/integer "cpp/types/integer")`, `[UINTMAX\_MAX](../../types/integer "cpp/types/integer")`, or `​0​` is returned, as appropriate. If no conversion can be performed, `​0​` is returned. ### Example ``` #include <iostream> #include <string> #include <cinttypes> int main() { std::wstring str = L"helloworld"; std::intmax_t val = std::wcstoimax(str.c_str(), nullptr, 36); std::wcout << str << " in base 36 is " << val << " in base 10\n"; wchar_t* nptr; val = std::wcstoimax(str.c_str(), &nptr, 30); if(nptr != &str[0] + str.size()) std::wcout << str << " in base 30 is invalid." << " The first invalid digit is " << *nptr << '\n'; } ``` Output: ``` helloworld in base 36 is 1767707668033969 in base 10 helloworld in base 30 is invalid. The first invalid digit is w ``` ### See also | | | | --- | --- | | [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) | | [wcstolwcstoll](wcstol "cpp/string/wide/wcstol") | converts a wide string to an integer value (function) | | [wcstoulwcstoull](wcstoul "cpp/string/wide/wcstoul") | converts a wide string to an unsigned integer value (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wcstoimax "c/string/wide/wcstoimax") for `wcstoimax, wcstoumax` | cpp std::iswspace std::iswspace ============= | Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | | | --- | --- | --- | | ``` int iswspace( wint_t ch ); ``` | | | Checks if the given wide character is a wide whitespace character as classified by the currently installed C locale. In the default locale, the whitespace characters are the following: * space (`0x20`, `' '`) * form feed (`0x0c`, `'\f'`) * line feed (`0x0a`, `'\n'`) * carriage return (`0x0d`, `'\r'`) * horizontal tab (`0x09`, `'\t'`) * vertical tab (`0x0b`, `'\v'`) 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 whitespace character, zero otherwise. ### Notes ISO 30112 defines POSIX space characters as Unicode characters U+0009..U+000D, U+0020, U+1680, U+180E, U+2000..U+2006, U+2008..U+200A, U+2028, U+2029, U+205F, and U+3000. ### Example Demonstrates the use of `iswspace()` with different locales. ``` #include <iostream> #include <clocale> #include <cwctype> void try_with(wchar_t c, const char* loc) { std::setlocale(LC_ALL, loc); std::wcout << "isspace('" << c << "') in " << loc << " locale returned " << std::boolalpha << (bool)std::iswspace(c) << '\n'; } int main() { wchar_t EM_SPACE = L'\u2003'; // Unicode character 'EM SPACE' try_with(EM_SPACE, "C"); try_with(EM_SPACE, "en_US.UTF8"); } ``` Output: ``` isspace(' ') in C locale returned false isspace(' ') in en_US.UTF8 locale returned true ``` ### See also | | | | --- | --- | | [isspace(std::locale)](../../locale/isspace "cpp/locale/isspace") | checks if a character is classified as whitespace by a locale (function template) | | [isspace](../byte/isspace "cpp/string/byte/isspace") | checks if a character is a space character (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/iswspace "c/string/wide/iswspace") for `iswspace` | | 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`**. | [`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`](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`** |
programming_docs
cpp std::wmemcpy std::wmemcpy ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wchar_t* wmemcpy( wchar_t* dest, const wchar_t* src, std::size_t count ); ``` | | | Copies exactly `count` successive wide characters from the wide character array pointed to by `src` to the wide character array pointed to by `dest`. If the objects overlap, the behavior is undefined. If `count` is zero, the function does nothing. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the wide character array to copy to | | src | - | pointer to the wide character array to copy from | | count | - | number of wide characters to copy | ### Return value `dest`. ### Notes This function's analog for byte strings is `[std::strncpy](../byte/strncpy "cpp/string/byte/strncpy")`, not `[std::strcpy](../byte/strcpy "cpp/string/byte/strcpy")`. This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it copies: nulls as well as invalid characters are copied too. ### Example ``` #include <iostream> #include <cwchar> #include <clocale> #include <locale> int main(void) { wchar_t from1[] = L"नमस्ते"; const size_t sz1 = sizeof from1 / sizeof *from1; wchar_t from2[] = L"Բարև"; const size_t sz2 = sizeof from2 / sizeof *from2; wchar_t to[sz1 + sz2]; std::wmemcpy(to, from1, sz1); // copy from1, along with its null terminator std::wmemcpy(to + sz1, from2, sz2); // append from2, along with its null terminator std::setlocale(LC_ALL, "en_US.utf8"); std::cout.imbue(std::locale("en_US.utf8")); std::wcout << "Wide array contains: "; for(size_t n = 0; n < sizeof to / sizeof *to; ++n) if(to[n]) std::wcout << to[n]; else std::wcout << "\\0"; std::wcout << '\n'; } ``` Possible output: ``` Wide array contains: नमस्ते\0Բարև\0 ``` ### See also | | | | --- | --- | | [strncpy](../byte/strncpy "cpp/string/byte/strncpy") | copies a certain amount of characters from one string to another (function) | | [wmemmove](wmemmove "cpp/string/wide/wmemmove") | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wmemcpy "c/string/wide/wmemcpy") for `wmemcpy` | cpp std::wmemmove std::wmemmove ============= | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` wchar_t* wmemmove( wchar_t* dest, const wchar_t* src, std::size_t count ); ``` | | | Copies exactly `count` successive wide characters from the wide character array pointed to by `src` to the wide character array pointed to by `dest`. If `count` is zero, the function does nothing. The arrays may overlap: copying takes place as if the wide characters were copied to a temporary wide character array and then copied from the temporary array to `dest`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the wide character array to copy to | | src | - | pointer to the wide character array to copy from | | count | - | number of wide characters to copy | ### 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 copies: nulls as well as invalid characters are copied too. ### Example ``` #include <iostream> #include <cwchar> #include <locale> #include <clocale> int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); wchar_t str[] = L"αβγδεζηθικλμνξοπρστυφχψω"; std::wcout << str << '\n'; std::wmemmove(str+4, str+3, 3); // copy from [δεζ] to [εζη] std::wcout << str << '\n'; } ``` Possible output: ``` αβγδεζηθικλμνξοπρστυφχψω αβγδδεζθικλμνξοπρστυφχψω ``` ### See also | | | | --- | --- | | [wmemcpy](wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) | | [memmove](../byte/memmove "cpp/string/byte/memmove") | moves one buffer to another (function) | | [copycopy\_if](../../algorithm/copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [copy\_backward](../../algorithm/copy_backward "cpp/algorithm/copy backward") | copies a range of elements in backwards order (function template) | | [C documentation](https://en.cppreference.com/w/c/string/wide/wmemmove "c/string/wide/wmemmove") for `wmemmove` | cpp std::basic_string_view<CharT,Traits>::compare std::basic\_string\_view<CharT,Traits>::compare =============================================== | | | | | --- | --- | --- | | ``` constexpr int compare( basic_string_view v ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr int compare( size_type pos1, size_type count1, basic_string_view v ) const; ``` | (2) | (since C++17) | | ``` constexpr int compare( size_type pos1, size_type count1, basic_string_view v, size_type pos2, size_type count2 ) const; ``` | (3) | (since C++17) | | ``` constexpr int compare( const CharT* s ) const; ``` | (4) | (since C++17) | | ``` constexpr int compare( size_type pos1, size_type count1, const CharT* s ) const; ``` | (5) | (since C++17) | | ``` constexpr int compare( size_type pos1, size_type count1, const CharT* s, size_type count2 ) const; ``` | (6) | (since C++17) | Compares two character sequences. 1) The length `rlen` of the sequences to compare is the smaller of `size()` and `v.size()`. The function compares the two views by calling `traits::compare(data(), v.data(), rlen)`, and returns a value according to the following table: | Condition | Result | Return value | | --- | --- | --- | | `Traits::compare(data(), v.data(), rlen) < 0` | `this` is *less* than `v` | `<0` | | `Traits::compare(data(), v.data(), rlen) == 0` | `size() < v.size()` | `this` is *less* than `v` | `<0` | | `size() == v.size()` | `this` is *equal* to `v` | `​0​` | | `size() > v.size()` | `this` is *greater* than `v` | `>0` | | `Traits::compare(data(), v.data(), rlen) > 0` | `this` is *greater* than `v` | `>0` | 2) Equivalent to `substr(pos1, count1).compare(v)`. 3) Equivalent to `substr(pos1, count1).compare(v.substr(pos2, count2))`. 4) Equivalent to `compare(basic_string_view(s))`. 5) Equivalent to `substr(pos1, count1).compare(basic_string_view(s))`. 6) Equivalent to `substr(pos1, count1).compare(basic_string_view(s, count2))`. ### Parameters | | | | | --- | --- | --- | | v | - | view to compare | | s | - | pointer to the character string to compare to | | count1 | - | number of characters of this view to compare | | pos1 | - | position of the first character in this view to compare | | count2 | - | number of characters of the given view to compare | | pos2 | - | position of the first character of the given view to compare | ### Return value negative value if this view is less than the other character sequence, zero if the both character sequences are equal, positive value if this view is greater than the other character sequence. ### Complexity 1) Linear in the number of characters compared. ### Example ``` #include <string_view> int main() { using std::operator""sv; static_assert( "abc"sv.compare("abcd"sv) < 0 ); static_assert( "abcd"sv.compare("abc"sv) > 0 ); static_assert( "abc"sv.compare("abc"sv) == 0 ); static_assert( ""sv.compare(""sv) == 0 ); } ``` ### See also | | | | --- | --- | | [compare](../basic_string/compare "cpp/string/basic string/compare") | compares two strings (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [operator==operator!=operator<operator>operator<=operator>=operator<=>](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) | cpp std::basic_string_view<CharT,Traits>::contains std::basic\_string\_view<CharT,Traits>::contains ================================================ | | | | | --- | --- | --- | | ``` constexpr bool contains( basic_string_view sv ) const noexcept; ``` | (1) | (since C++23) | | ``` constexpr bool contains( CharT c ) const noexcept; ``` | (2) | (since C++23) | | ``` constexpr bool contains( const CharT* s ) const; ``` | (3) | (since C++23) | Checks if the string view contains the given substring, where. 1) the substring is a string view. 2) the substring is a single character. 3) the substring is a null-terminated character string. All three overloads are equivalent to `return find(x) != npos;`, where `x` is the parameter. ### Parameters | | | | | --- | --- | --- | | sv | - | a string view | | c | - | a single character | | s | - | a null-terminated character string | ### Return value `true` if the string view contains the provided substring, `false` otherwise. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_string_contains`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string_view> auto main() -> int { using namespace std::literals; std::cout << std::boolalpha // bool contains(basic_string_view x) const noexcept; << "https://cppreference.com"sv.contains("cpp"sv) << ' ' // true << "https://cppreference.com"sv.contains("java"sv) << ' ' // false // bool contains(CharT x) const noexcept; << "C++23"sv.contains('+') << ' ' // true << "C++23"sv.contains('-') << ' ' // false // bool contains(const CharT* x) const; << std::string_view("basic_string_view").contains("string") << ' ' // true << std::string_view("basic_string_view").contains("String") << ' ' // false << '\n'; } ``` Output: ``` true false true false true false ``` ### See also | | | | --- | --- | | [starts\_with](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](ends_with "cpp/string/basic string view/ends with") (C++20) | checks if the string view ends with the given suffix (public member function) | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [substr](substr "cpp/string/basic string view/substr") (C++17) | returns a substring (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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::size, std::basic_string_view<CharT,Traits>::length std::basic\_string\_view<CharT,Traits>::size, std::basic\_string\_view<CharT,Traits>::length ============================================================================================ | | | | | --- | --- | --- | | ``` constexpr size_type size() const noexcept; ``` | | (since C++17) | | ``` constexpr size_type length() const noexcept; ``` | | (since C++17) | Returns the number of `CharT` elements in the view, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of `CharT` elements in the view. ### Complexity Constant. ### Example ``` #include <string_view> #include <iostream> void check_string(std::string_view ref) { // Print a string surrounded by single quotes, its length // and whether it is considered empty. std::cout << std::boolalpha << "'" << ref << "' has " << ref.size() << " character(s); emptiness: " << ref.empty() << '\n'; } int main(int argc, char **argv) { // An empty string check_string(""); // Almost always not empty: argv[0] if (argc > 0) check_string(argv[0]); } ``` Possible output: ``` '' has 0 character(s); emptiness: true './a.out' has 7 character(s); emptiness: false ``` ### See also | | | | --- | --- | | [empty](empty "cpp/string/basic string view/empty") (C++17) | checks whether the view is empty (public member function) | | [max\_size](max_size "cpp/string/basic string view/max size") (C++17) | returns the maximum number of characters (public member function) | | [sizelength](../basic_string/size "cpp/string/basic string/size") | returns the number of characters (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp deduction guides for std::basic_string_view deduction guides for `std::basic_string_view` ============================================= | Defined in header `[<string\_view>](../../header/string_view "cpp/header/string view")` | | | | --- | --- | --- | | ``` template<class It, class End> basic_string_view(It, End) -> basic_string_view<std::iter_value_t<It>>; ``` | (1) | (since C++20) | | ``` template<class R> basic_string_view(R&&) -> basic_string_view<ranges::range_value_t<R>>; ``` | (2) | (since C++23) | These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`. 1) This deduction guide allow the character type to be deduced from the iterator-sentinel pair. This overload participates in overload resolution only if `It` satisfies [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and `End` satisfies [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") for `It`. 2) This deduction guide allow the character type to be deduced from the range. This overload participates in overload resolution only if `R` satisfies [`contiguous_range`](../../ranges/contiguous_range "cpp/ranges/contiguous range"). ### Example ``` #include <array> #include <iostream> #include <string_view> int main() { std::array a1 {'n', 'u', 'c', 'l', 'e', 'o', 'n', 's', ':', '\n'}; std::basic_string_view s1(a1.cbegin(), a1.cend()); // deduction: CharT -> char static_assert(std::is_same_v<decltype(s1)::value_type, char>); std::cout << s1; std::array a2 {L'p', L'r', L'o', L't', L'o', L'n', L's', L'\n'}; std::basic_string_view s2(a2.cbegin(), a2.cend()); // deduction: CharT -> wchar_t static_assert(std::is_same_v<decltype(s2)::value_type, wchar_t>); std::wcout << s2; std::array<long, 9> a3 {'n', 'e', 'u', 't', 'r', 'o', 'n', 's', '\n'}; std::basic_string_view s3(a3.cbegin(), a3.cend()); // deduction: CharT -> long static_assert(std::is_same_v<decltype(s3)::value_type, long>); for (const auto e : s3) { std::cout << static_cast<char>(e); } } ``` Output: ``` nucleons: protons neutrons ``` cpp std::basic_string_view<CharT,Traits>::ends_with std::basic\_string\_view<CharT,Traits>::ends\_with ================================================== | | | | | --- | --- | --- | | ``` constexpr bool ends_with( basic_string_view sv ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr bool ends_with( CharT c ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr bool ends_with( const CharT* s ) const; ``` | (3) | (since C++20) | Checks if the string view ends with the given suffix, where. 1) the suffix is a string view. Effectively returns `size() >= sv.size() && compare(size() - sv.size(), npos, sv) == 0` 2) the suffix is a single character. Effectively returns `!empty() && Traits::eq(back(), c)` 3) the suffix is a null-terminated character string. Effectively returns `ends_with(basic_string_view(s))` ### Parameters | | | | | --- | --- | --- | | sv | - | a string view which may be a result of implicit conversion from `std::basic_string` | | c | - | a single character | | s | - | a null-terminated character string | ### Return value `true` if the string view ends with the provided suffix, `false` otherwise. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_starts_ends_with`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string_view> auto main() -> int { using namespace std::literals; std::cout << std::boolalpha // (1) bool ends_with( basic_string_view sv ) const noexcept; << std::string_view("https://cppreference.com").ends_with(".com"sv) << ' ' // true << std::string_view("https://cppreference.com").ends_with(".org"sv) << ' ' // false // (2) bool ends_with( CharT c ) const noexcept; << std::string_view("C++20").ends_with('0') << ' ' // true << std::string_view("C++20").ends_with('3') << ' ' // false // (3) bool ends_with( const CharT* s ) const; << std::string_view("string_view").ends_with("view") << ' ' // true << std::string_view("string_view").ends_with("View") << ' ' // false << '\n'; } ``` Output: ``` true false true false true false ``` ### See also | | | | --- | --- | | [starts\_with](starts_with "cpp/string/basic string view/starts with") (C++20) | checks if the string view starts with the given prefix (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 of `std::basic_string<CharT,Traits,Allocator>`) | | [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 of `std::basic_string<CharT,Traits,Allocator>`) | | [contains](../basic_string/contains "cpp/string/basic string/contains") (C++23) | checks if the string contains the given substring or character (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [contains](contains "cpp/string/basic string view/contains") (C++23) | checks if the string view contains the given substring or character (public member function) | | [compare](compare "cpp/string/basic string view/compare") (C++17) | compares two views (public member function) | cpp std::literals::string_view_literals::operator""sv std::literals::string\_view\_literals::operator""sv =================================================== | Defined in header `[<string\_view>](../../header/string_view "cpp/header/string view")` | | | | --- | --- | --- | | ``` constexpr std::string_view operator "" sv( const char* str, std::size_t len ) noexcept; ``` | (1) | (since C++17) | | ``` constexpr std::u8string_view operator "" sv( const char8_t* str, std::size_t len ) noexcept; ``` | (2) | (since C++20) | | ``` constexpr std::u16string_view operator "" sv( const char16_t* str, std::size_t len ) noexcept; ``` | (3) | (since C++17) | | ``` constexpr std::u32string_view operator "" sv( const char32_t* str, std::size_t len ) noexcept; ``` | (4) | (since C++17) | | ``` constexpr std::wstring_view operator "" sv( const wchar_t* str, std::size_t len ) noexcept; ``` | (5) | (since C++17) | Forms a string view of a character literal. 1) returns `[std::string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view){str, len}` 2) returns `[std::u8string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view){str, len}` 3) returns `[std::u16string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view){str, len}` 4) returns `[std::u32string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view){str, len}` 5) returns `[std::wstring\_view](http://en.cppreference.com/w/cpp/string/basic_string_view){str, len}` ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the beginning of the raw character array literal | | len | - | length of the raw character array literal | ### Return value The string\_view literal. ### Notes These operators are declared in the namespace `std::literals::string_view_literals`, where both `literals` and `string_view_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::string_view_literals`, and `using namespace std::literals::string_view_literals`. ### Example ``` #include <string_view> #include <iostream> #include <typeinfo> void print_all(const std::string_view sw) { for (char c : sw) std::cout << (c == '\0' ? '?' : c); std::cout << '\n'; } int main() { using namespace std::literals; std::string_view s1 = "abc\0\0def"; std::string_view s2 = "abc\0\0def"sv; std::cout << "s1.size(): " << s1.size() << "; s1: "; print_all(s1); std::cout << "s2.size(): " << s2.size() << "; s2: "; print_all(s2); std::cout << "abcdef"sv.substr(1,4) << '\n'; auto value_type_info = []<typename T>(T) { using V = typename T::value_type; std::cout << "sizeof " << typeid(V).name() << ": " << sizeof(V) << '\n'; }; value_type_info( "char A"sv ); value_type_info( L"wchar_t ∀"sv ); value_type_info( u8"char8_t ∆"sv ); value_type_info( u"char16_t ∇"sv ); value_type_info( U"char32_t ∃"sv ); value_type_info( LR"(raw ⊞)"sv ); } ``` Possible output: ``` s1.size(): 3; s1: abc s2.size(): 8; s2: abc??def bcde sizeof char: 1 sizeof wchar_t: 4 sizeof char8_t: 1 sizeof char16_t: 2 sizeof char32_t: 4 sizeof wchar_t: 4 ``` ### See also | | | | --- | --- | | [(constructor)](basic_string_view "cpp/string/basic string view/basic string view") (C++17) | constructs a `basic_string_view` (public member function) | | [operator""s](../basic_string/operator%22%22s "cpp/string/basic string/operator\"\"s") (C++14) | Converts a character array literal to `basic_string` (function) |
programming_docs
cpp operator<<(std::basic_string_view) operator<<(std::basic\_string\_view) ==================================== | Defined in header `[<string\_view>](../../header/string_view "cpp/header/string view")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, std::basic_string_view <CharT, Traits> v ); ``` | | (since C++17) | Behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). After constructing and checking the sentry object, determines the output format padding as follows: a) If `v.size()` is not less than `os.width()`, uses the range `[v.begin(), v.end())` as-is b) Otherwise, if `(os.flags() & ios_base::adjustfield) == ios_base::left`, places `os.width()-v.size()` copies of the `os.fill()` character after the character sequence c) Otherwise, places `os.width()-v.size()` copies of the `os.fill()` character before the character sequence Then stores each character from the resulting sequence (the contents of `v` plus padding) to the output stream `os` as if by calling `os.rdbuf()->sputn(seq, n)`, where `n=[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(os.width(), str.size())`. Finally, calls `os.width(0)` to cancel the effects of `[std::setw](../../io/manip/setw "cpp/io/manip/setw")`, if any. ### Exceptions May throw `[std::ios\_base::failure](../../io/ios_base/failure "cpp/io/ios base/failure")` if an exception is thrown during output. ### Parameters | | | | | --- | --- | --- | | os | - | a character output stream | | v | - | the view to be inserted | ### Return value `os`. ### Example ``` #include <iomanip> #include <iostream> #include <string_view> int main() { constexpr std::string_view s{"abc"}; constexpr int width{5}; constexpr char fill{'-'}; std::cout << std::setfill(fill) << "[" << s << "]\n" << "[" << std::left << std::setw(width) << s << "]\n" << "[" << std::right << std::setw(width) << s << "]\n"; } ``` Output: ``` [abc] [abc--] [--abc] ``` ### See also | | | | --- | --- | | [operator<<operator>>](../basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function template) | cpp std::basic_string_view<CharT,Traits>::rbegin, std::basic_string_view<CharT,Traits>::crbegin std::basic\_string\_view<CharT,Traits>::rbegin, std::basic\_string\_view<CharT,Traits>::crbegin =============================================================================================== | | | | | --- | --- | --- | | ``` constexpr const_reverse_iterator rbegin() const noexcept; ``` | | (since C++17) | | ``` constexpr const_reverse_iterator crbegin() const noexcept; ``` | | (since C++17) | Returns a reverse iterator to the first character of the reversed view. It corresponds to the last character of the non-reversed view. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value `const_reverse_iterator` to the first character. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <string_view> int main() { std::ostream_iterator<char> out_it(std::cout); std::string_view str_view("abcdef"); std::copy(str_view.rbegin(), std::next(str_view.rbegin(), 3), out_it); *out_it = '\n'; std::copy(str_view.crbegin(), std::next(str_view.crbegin(), 3), out_it); *out_it = '\n'; } ``` Output: ``` fed fed ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/string/basic string view/rend") (C++17) | returns a reverse 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::rfind std::basic\_string\_view<CharT,Traits>::rfind ============================================= | | | | | --- | --- | --- | | ``` constexpr size_type rfind( basic_string_view v, size_type pos = npos ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr size_type rfind( CharT c, size_type pos = npos ) const noexcept; ``` | (2) | (since C++17) | | ``` constexpr size_type rfind( const CharT* s, size_type pos, size_type count ) const; ``` | (3) | (since C++17) | | ``` constexpr size_type rfind( const CharT* s, size_type pos = npos ) const; ``` | (4) | (since C++17) | Finds the last substring equal to the given character sequence. Search begins at `pos`, i.e. the found substring must not begin in a position following `pos`. If `[npos](npos "cpp/string/basic string view/npos")` or any value not smaller than `[size()](size "cpp/string/basic string view/size")`-1 is passed as `pos`, whole string will be searched. 1) Finds the last occurrence of `v` in this view, starting at position `pos`. 2) Equivalent to `rfind(basic_string_view([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c), 1), pos)`. 3) Equivalent to `rfind(basic_string_view(s, count), pos)`. 4) Equivalent to `rfind(basic_string_view(s), pos)`. ### Parameters | | | | | --- | --- | --- | | v | - | view to search for | | pos | - | position at which to start the search | | count | - | length of substring to search for | | s | - | pointer to a character string to search for | | ch | - | character to search for | ### Return value Position of the first character of the found substring or `[npos](npos "cpp/string/basic string view/npos")` if no such substring is found. ### Complexity O(`[size()](size "cpp/string/basic string view/size")` \* v.`[size()](size "cpp/string/basic string view/size")`) at worst. ### Example ``` #include <string_view> int main() { using namespace std::literals; constexpr auto N = std::string_view::npos; static_assert(true && (6 == "AB AB AB"sv.rfind("AB")) && (6 == "AB AB AB"sv.rfind("ABCD", N, 2)) && (3 == "AB AB AB"sv.rfind("AB", 5)) && (2 == "B AB AB "sv.rfind("AB", 2)) && (N == "B AB AB "sv.rfind("AB", 1)) && (5 == "B AB AB "sv.rfind('A')) && (4 == "AB AB AB"sv.rfind('B', 4)) && (N == "AB AB AB"sv.rfind('C')) ); } ``` ### See also | | | | --- | --- | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string view/find first of") (C++17) | find first occurrence of characters (public member function) | | [find\_last\_of](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](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](find_last_not_of "cpp/string/basic string view/find last not of") (C++17) | find last absence of characters (public member function) | | [rfind](../basic_string/rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::at std::basic\_string\_view<CharT,Traits>::at ========================================== | | | | | --- | --- | --- | | ``` constexpr const_reference at( size_type pos ) const; ``` | | (since C++17) | Returns a `const` reference to the character at specified location `pos`. Bounds checking is performed, exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` will be thrown on invalid access. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the character to return | ### Return value `Const` reference to the requested character. ### Exceptions Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos >= size()`. ### Complexity Constant. ### Example ``` #include <iostream> #include <stdexcept> #include <string_view> int main() { std::string_view str_view("abcdef"); try { for (std::size_t i = 0; true; ++i) std::cout << i << ": " << str_view.at(i) << '\n'; } catch (const std::out_of_range& e) { std::cout << "Whooops. Index is out of range.\n"; std::cout << e.what() << '\n'; } } ``` Possible output: ``` 0: a 1: b 2: c 3: d 4: e 5: f 6: Whooops. Index is out of range. basic_string_view::at: __pos (which is 6) >= this->size() (which is 6) ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/string/basic string view/operator at") (C++17) | accesses the specified character (public member function) | | [at](../basic_string/at "cpp/string/basic string/at") | accesses the specified character with bounds checking (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::operator[] std::basic\_string\_view<CharT,Traits>::operator[] ================================================== | | | | | --- | --- | --- | | ``` constexpr const_reference operator[]( size_type pos ) const; ``` | | (since C++17) | Returns a const reference to the character at specified location `pos`. No bounds checking is performed: the behavior is undefined if `pos >= size()`. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the character to return | ### Return value Const reference to the requested character. ### Exceptions Does not throw. ### Complexity Constant. ### Notes Unlike `[std::basic\_string::operator[]](../basic_string/operator_at "cpp/string/basic string/operator at")`, `std::basic_string_view::operator[](size())` has undefined behavior instead of returning `CharT()`. ### Example ``` #include <iostream> #include <string_view> int main() { std::string str = "Exemplar"; std::string_view v = str; std::cout << v[2] << '\n'; // v[2] = 'y'; // Error: cannot modify through a string view str[2] = 'y'; std::cout << v[2] << '\n'; } ``` Output: ``` e y ``` ### See also | | | | --- | --- | | [at](at "cpp/string/basic string view/at") (C++17) | 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::swap std::basic\_string\_view<CharT,Traits>::swap ============================================ | | | | | --- | --- | --- | | ``` constexpr void swap( basic_string_view& v ) noexcept; ``` | | (since C++17) | Exchanges the view with that of `v`. ### Parameters | | | | | --- | --- | --- | | v | - | view to swap with | ### Return value (none). ### Complexity Constant. ### Example ``` #include <string_view> #include <iostream> int main() { auto s1{ std::string_view{"⏺⏺⏺⏺⏺"} }; auto s2{ std::string_view{"⏹⏹⏹⏹⏹"} }; std::cout << "Before : " << s1 << ' ' << s2 << "\n"; s1.swap(s2); std::cout << "After : " << s1 << ' ' << s2 << "\n"; } ``` Output: ``` Before : ⏺⏺⏺⏺⏺ ⏹⏹⏹⏹⏹ After : ⏹⏹⏹⏹⏹ ⏺⏺⏺⏺⏺ ``` ### 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) | | [swap](../basic_string/swap "cpp/string/basic string/swap") | swaps the contents (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::max_size std::basic\_string\_view<CharT,Traits>::max\_size ================================================= | | | | | --- | --- | --- | | ``` constexpr size_type max_size() const noexcept; ``` | | (since C++17) | The largest possible number of char-like objects that can be referred to by a `basic_string_view`. ### Parameters (none). ### Return value Maximum number of characters. ### Complexity Constant. ### Example ``` #include <iostream> #include <limits> #include <string_view> int main() { std::cout << std::numeric_limits<std::int64_t>::max() << " <- numeric_limits<int64_t>::max()\n" << std::string_view{}.max_size() << " <- std::string_view::max_size()\n" << std::basic_string_view<char>{}.max_size() << " <- std::basic_string_view<char>::max_size()\n" << std::basic_string_view<char16_t>{}.max_size() << " <- std::basic_string_view<char16_t>::max_size()\n" << std::wstring_view{}.max_size() << " <- std::wstring_view::max_size()\n" << std::basic_string_view<char32_t>{}.max_size() << " <- std::basic_string_view<char32_t>::max_size()\n" ; } ``` Possible output: ``` 9223372036854775807 <- numeric_limits<int64_t>::max() 4611686018427387899 <- std::string_view::max_size() 4611686018427387899 <- std::basic_string_view<char>::max_size() 2305843009213693949 <- std::basic_string_view<char16_t>::max_size() 1152921504606846974 <- std::wstring_view::max_size() 1152921504606846974 <- std::basic_string_view<char32_t>::max_size() ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string view/size") (C++17) | returns the number of characters (public member function) | | [empty](empty "cpp/string/basic string view/empty") (C++17) | checks whether the view is empty (public member function) | | [max\_size](../basic_string/max_size "cpp/string/basic string/max size") | returns the maximum number of characters (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::remove_prefix std::basic\_string\_view<CharT,Traits>::remove\_prefix ====================================================== | | | | | --- | --- | --- | | ``` constexpr void remove_prefix( size_type n ); ``` | | (since C++17) | Moves the start of the view forward by `n` characters. The behavior is undefined if `n > size()`. ### Parameters | | | | | --- | --- | --- | | n | - | number of characters to remove from the start of the view | ### Return value (none). ### Complexity Constant. ### Example ``` #include <iostream> #include <algorithm> #include <string_view> int main() { std::string str = " trim me"; std::string_view v = str; v.remove_prefix(std::min(v.find_first_not_of(" "), v.size())); std::cout << "String: '" << str << "'\n" << "View : '" << v << "'\n"; } ``` Output: ``` String: ' trim me' View : 'trim me' ``` ### See also | | | | --- | --- | | [remove\_suffix](remove_suffix "cpp/string/basic string view/remove suffix") (C++17) | shrinks the view by moving its end backward (public member function) | cpp std::basic_string_view<CharT,Traits>::find_last_of std::basic\_string\_view<CharT,Traits>::find\_last\_of ====================================================== | | | | | --- | --- | --- | | ``` constexpr size_type find_last_of( basic_string_view v, size_type pos = npos ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr size_type find_last_of( CharT c, size_type pos = npos ) const noexcept; ``` | (2) | (since C++17) | | ``` constexpr size_type find_last_of( const CharT* s, size_type pos, size_type count ) const; ``` | (3) | (since C++17) | | ``` constexpr size_type find_last_of( const CharT* s, size_type pos = npos ) const; ``` | (4) | (since C++17) | Finds the last character equal to one of characters in the given character sequence. Exact search algorithm is not specified. The search considers only the interval [0; pos]. If the character is not present in the interval, `[npos](npos "cpp/string/basic string view/npos")` will be returned. 1) Finds the last occurence of any of the characters of `v` in this view, ending at position `pos`. 2) Equivalent to `find_last_of(basic_string_view([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c), 1), pos)`. 3) Equivalent to `find_last_of(basic_string_view(s, count), pos)`. 4) Equivalent to `find_last_of(basic_string_view(s), pos)`. ### Parameters | | | | | --- | --- | --- | | v | - | view to search for | | pos | - | position at which the search is to finish | | count | - | length of the string of characters to search for | | s | - | pointer to a string of characters to search for | | ch | - | character to search for | ### Return value Position of the last occurrence of any character of the substring, or `[npos](npos "cpp/string/basic string view/npos")` if no such character is found. ### Complexity O(`size()` \* `v.size()`) at worst. ### Example ``` #include <string_view> #include <iostream> int main() { using namespace std::literals; constexpr auto N = std::string_view::npos; static_assert( 5 == "delete"sv.find_last_of("cdef"sv) && // └────────────────────┘ N == "double"sv.find_last_of("fghi"sv) && // 0 == "else"sv.find_last_of("bcde"sv, 2 /* pos [0..2]: "els" */) && // └────────────────────────┘ N == "explicit"sv.find_last_of("abcd"sv, 4 /* pos [0..4]: "expli" */) && // 3 == "extern"sv.find_last_of('e') && // └────────────────────┘ N == "false"sv.find_last_of('x') && // 0 == "inline"sv.find_last_of('i', 2 /* pos [0..2]: "inl" */) && // └───────────────────────┘ N == "mutable"sv.find_last_of('a', 2 /* pos [0..2]: "mut" */) && // 3 == "namespace"sv.find_last_of("cdef", 3 /* pos [0..3]: "name" */, 3 /* "cde" */) && // └─────────────────────────┘ N == "namespace"sv.find_last_of("cdef", 3 /* pos [0..3]: "name" */, 2 /* "cd" */) ); std::cout << "All tests passed.\n"; } ``` Output: ``` All tests passed. ``` ### See also | | | | --- | --- | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [rfind](rfind "cpp/string/basic string view/rfind") (C++17) | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string view/find first of") (C++17) | find first occurrence of characters (public member function) | | [find\_first\_not\_of](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](find_last_not_of "cpp/string/basic string view/find last not of") (C++17) | find last 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::back std::basic\_string\_view<CharT,Traits>::back ============================================ | | | | | --- | --- | --- | | ``` constexpr const_reference back() const; ``` | | (since C++17) | Returns reference to the last character in the view. The behavior is undefined if `empty() == true`. ### Parameters (none). ### Return value Reference to the last character, equivalent to `operator[](size() - 1)`. ### Complexity Constant. ### Example ``` #include <string_view> #include <iostream> int main() { for (std::string_view str{"ABCDEF"}; !str.empty(); str.remove_suffix(1)) std::cout << str.back() << ' ' << str << '\n'; } ``` Output: ``` F ABCDEF E ABCDE D ABCD C ABC B AB A A ``` ### See also | | | | --- | --- | | [front](front "cpp/string/basic string view/front") (C++17) | accesses the first character (public member function) | | [empty](empty "cpp/string/basic string view/empty") (C++17) | checks whether the view is empty (public member function) | | [back](../basic_string/back "cpp/string/basic string/back") (C++11) | accesses the last character (public member function of `std::basic_string<CharT,Traits,Allocator>`) |
programming_docs
cpp std::basic_string_view<CharT,Traits>::data std::basic\_string\_view<CharT,Traits>::data ============================================ | | | | | --- | --- | --- | | ``` constexpr const_pointer data() const noexcept; ``` | | (since C++17) | Returns a pointer to the underlying character array. The pointer is such that the range [data(); data() + size()) is valid and the values in it correspond to the values of the view. ### Parameters (none). ### Return value A pointer to the underlying character array. ### Complexity Constant. ### Notes Unlike `[std::basic\_string::data()](../basic_string/data "cpp/string/basic string/data")` and string literals, `data()` may return a pointer to a buffer that is not null-terminated. Therefore it is typically a mistake to pass `data()` to a routine that takes just a `const CharT*` and expects a null-terminated string. ### Example ``` #include <iostream> #include <cstring> #include <cwchar> #include <string> #include <string_view> int main() { std::wstring_view wcstr_v = L"xyzzy"; std::cout << std::wcslen(wcstr_v.data()) << '\n'; // OK: the underlying character array is null-terminated char array[3] = {'B', 'a', 'r'}; std::string_view array_v(array, sizeof array); // std::cout << std::strlen(array_v.data()) << '\n'; // error: the underlying character array is not null-terminated std::string str(array_v.data(), array_v.size()); // OK std::cout << std::strlen(str.data()) << '\n'; // OK: the underlying character array of a std::string is always null-terminated } ``` Output: ``` 5 3 ``` ### See also | | | | --- | --- | | [front](front "cpp/string/basic string view/front") (C++17) | accesses the first character (public member function) | | [back](back "cpp/string/basic string view/back") (C++17) | 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::find std::basic\_string\_view<CharT,Traits>::find ============================================ | | | | | --- | --- | --- | | ``` constexpr size_type find( basic_string_view v, size_type pos = 0 ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr size_type find( CharT ch, size_type pos = 0 ) const noexcept; ``` | (2) | (since C++17) | | ``` constexpr size_type find( const CharT* s, size_type pos, size_type count ) const; ``` | (3) | (since C++17) | | ``` constexpr size_type find( const CharT* s, size_type pos = 0 ) const; ``` | (4) | (since C++17) | Finds the first substring equal to the given character sequence. 1) Finds the first occurence of `v` in this view, starting at position `pos`. 2) Equivalent to `find(basic_string_view([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(ch), 1), pos)`. 3) Equivalent to `find(basic_string_view(s, count), pos)`. 4) Equivalent to `find(basic_string_view(s), pos)`. ### Parameters | | | | | --- | --- | --- | | v | - | view to search for | | pos | - | position at which to start the search | | count | - | length of substring to search for | | s | - | pointer to a character string to search for | | ch | - | character to search for | ### Return value Position of the first character of the found substring, or `[npos](npos "cpp/string/basic string view/npos")` if no such substring is found. ### Complexity O(`size()` \* `v.size()`) at worst. ### Example ``` #include <string_view> int main() { using namespace std::literals; constexpr auto str{" long long int;"sv}; static_assert( 1 == str.find("long"sv) && "<- find(v , pos = 0)" && 6 == str.find("long"sv, 2) && "<- find(v , pos = 2)" && 0 == str.find(' ') && "<- find(ch, pos = 0)" && 2 == str.find('o', 1) && "<- find(ch, pos = 1)" && 2 == str.find("on") && "<- find(s , pos = 0)" && 6 == str.find("long double", 5, 4) && "<- find(s , pos = 5, count = 4)" ); static_assert(str.npos == str.find("float")); } ``` ### See also | | | | --- | --- | | [rfind](rfind "cpp/string/basic string view/rfind") (C++17) | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string view/find first of") (C++17) | find first occurrence of characters (public member function) | | [find\_last\_of](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](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](find_last_not_of "cpp/string/basic string view/find last not of") (C++17) | find last absence of characters (public member function) | | [find](../basic_string/find "cpp/string/basic string/find") | find characters in the string (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::find_last_not_of std::basic\_string\_view<CharT,Traits>::find\_last\_not\_of =========================================================== | | | | | --- | --- | --- | | ``` constexpr size_type find_last_not_of( basic_string_view v, size_type pos = npos ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr size_type find_last_not_of( CharT c, size_type pos = npos ) const noexcept; ``` | (2) | (since C++17) | | ``` constexpr size_type find_last_not_of( const CharT* s, size_type pos, size_type count ) const; ``` | (3) | (since C++17) | | ``` constexpr size_type find_last_not_of( const CharT* s, size_type pos = npos ) const; ``` | (4) | (since C++17) | Finds the last character not equal to any of the characters in the given character sequence. The search considers only the interval [0, pos]. 1) Finds the last character not equal to any of the characters of `v` in this view, starting at position `pos`. 2) Equivalent to `find_last_not_of(basic_string_view([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c), 1), pos)`. 3) Equivalent to `find_last_not_of(basic_string_view(s, count), pos)`. 4) Equivalent to `find_last_not_of(basic_string_view(s), pos)`. ### Parameters | | | | | --- | --- | --- | | v | - | view to search for | | pos | - | position at which to start the search | | count | - | length of the string of characters to compare | | s | - | pointer to a string of characters to compare | | ch | - | character to compare | ### Return value Position of the last character not equal to any of the characters in the given string, or `[npos](npos "cpp/string/basic string view/npos")` if no such character is found. ### Complexity O(`size()` \* `v.size()`) at worst. ### Example ``` #include <string_view> using std::operator""sv; int main() { static_assert(1 == "BCDEF"sv.find_last_not_of("DEF")); // ^ static_assert(2 == "BCDEFG"sv.find_last_not_of("EFG", 3)); // ^ static_assert(2 == "ABBA"sv.find_last_not_of('A')); // ^ static_assert(1 == "ABBA"sv.find_last_not_of('A', 1)); // ^ } ``` ### See also | | | | --- | --- | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [rfind](rfind "cpp/string/basic string view/rfind") (C++17) | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string view/find first of") (C++17) | find first occurrence of characters (public member function) | | [find\_last\_of](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](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/find_last_not_of "cpp/string/basic string/find last not of") | find last absence of characters (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::starts_with std::basic\_string\_view<CharT,Traits>::starts\_with ==================================================== | | | | | --- | --- | --- | | ``` constexpr bool starts_with( basic_string_view sv ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr bool starts_with( CharT c ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr bool starts_with( const CharT* s ) const; ``` | (3) | (since C++20) | Checks if the string view begins with the given prefix, where. 1) the prefix is a string view. Effectively returns `substr(0, sv.size()) == sv` 2) the prefix is a single character. Effectively returns `!empty() && Traits::eq(front(), c)` 3) the prefix is a null-terminated character string. Effectively returns `starts_with(basic_string_view(s))` ### Parameters | | | | | --- | --- | --- | | sv | - | a string view which may be a result of implicit conversion from `std::basic_string` | | c | - | a single character | | s | - | a null-terminated character string | ### Return value `true` if the string view begins with the provided prefix, `false` otherwise. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_starts_ends_with`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string_view> auto main() -> int { using namespace std::literals; std::cout << std::boolalpha // bool starts_with(basic_string_view x) const noexcept; << "https://cppreference.com"sv.starts_with("http"sv) << ' ' // true << "https://cppreference.com"sv.starts_with("ftp"sv) << ' ' // false // bool starts_with(CharT x) const noexcept; << "C++20"sv.starts_with('C') << ' ' // true << "C++20"sv.starts_with('J') << ' ' // false // bool starts_with(const CharT* x) const; << std::string_view("string_view").starts_with("string") << ' ' // true << std::string_view("string_view").starts_with("String") << ' ' // false << '\n'; } ``` Output: ``` true false true false true false ``` ### See also | | | | --- | --- | | [ends\_with](ends_with "cpp/string/basic string view/ends with") (C++20) | checks if the string view ends with the given suffix (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 of `std::basic_string<CharT,Traits,Allocator>`) | | [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 of `std::basic_string<CharT,Traits,Allocator>`) | | [contains](../basic_string/contains "cpp/string/basic string/contains") (C++23) | checks if the string contains the given substring or character (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [contains](contains "cpp/string/basic string view/contains") (C++23) | checks if the string view contains the given substring or character (public member function) | | [compare](compare "cpp/string/basic string view/compare") (C++17) | compares two views (public member function) | cpp std::basic_string_view<CharT,Traits>::remove_suffix std::basic\_string\_view<CharT,Traits>::remove\_suffix ====================================================== | | | | | --- | --- | --- | | ``` constexpr void remove_suffix( size_type n ); ``` | | (since C++17) | Moves the end of the view back by `n` characters. The behavior is undefined if `n > size()`. ### Parameters | | | | | --- | --- | --- | | n | - | number of characters to remove from the end of the view | ### Return value (none). ### Complexity Constant. ### Example ``` #include <iostream> #include <string_view> int main() { char arr[] = {'a', 'b', 'c', 'd', '\0', '\0', '\0'}; std::string_view v(arr, sizeof arr); auto trim_pos = v.find('\0'); if(trim_pos != v.npos) v.remove_suffix(v.size() - trim_pos); std::cout << "Array: '" << arr << "', size=" << sizeof arr << '\n' << "View : '" << v << "', size=" << v.size() << '\n'; } ``` Output: ``` Array: 'abcd', size=7 View : 'abcd', size=4 ``` ### See also | | | | --- | --- | | [remove\_prefix](remove_prefix "cpp/string/basic string view/remove prefix") (C++17) | shrinks the view by moving its start forward (public member function) | cpp std::basic_string_view<CharT,Traits>::npos std::basic\_string\_view<CharT,Traits>::npos ============================================ | | | | | --- | --- | --- | | ``` static constexpr size_type npos = size_type(-1); ``` | | (since C++17) | This is a special value equal to the maximum value representable by the type `size_type`. The exact meaning depends on context, but it is generally used either as end of view indicator by the functions that expect a view index or as the error indicator by the functions that return a view index. ### Example ``` #include <string_view> constexpr bool contains(std::string_view const what, std::string_view const where) noexcept { return std::string_view::npos != where.find(what); } int main() { using namespace std::literals; static_assert(contains("water", "in a bottle of water")); static_assert(!contains("wine", "in a bottle of champagne")); static_assert(""sv.npos == "haystack"sv.find("needle")); } ``` ### See also | | | | --- | --- | | [npos](../basic_string/npos "cpp/string/basic string/npos") [static] | special value. The exact meaning depends on the context (public static member constant of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::front std::basic\_string\_view<CharT,Traits>::front ============================================= | | | | | --- | --- | --- | | ``` constexpr const_reference front() const; ``` | | (since C++17) | Returns reference to the first character in the view. The behavior is undefined if `empty() == true`. ### Parameters (none). ### Return value reference to the first character, equivalent to `operator[](0)`. ### Complexity Constant. ### Example ``` #include <string_view> #include <iostream> int main() { for (std::string_view str{"ABCDEF"}; !str.empty(); str.remove_prefix(1)) std::cout << str.front() << ' ' << str << '\n'; } ``` Output: ``` A ABCDEF B BCDEF C CDEF D DEF E EF F F ``` ### See also | | | | --- | --- | | [back](back "cpp/string/basic string view/back") (C++17) | accesses the last character (public member function) | | [empty](empty "cpp/string/basic string view/empty") (C++17) | checks whether the view is empty (public member function) | | [front](../basic_string/front "cpp/string/basic string/front") (C++11) | accesses the first character (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::operator= std::basic\_string\_view<CharT,Traits>::operator= ================================================= | | | | | --- | --- | --- | | ``` constexpr basic_string_view& operator=( const basic_string_view& view ) noexcept = default; ``` | | (since C++17) | Replaces the view with that of `view`. ### Parameters | | | | | --- | --- | --- | | view | - | view to copy | ### Return value `*this`. ### Complexity Constant. ### Example ``` #include <iostream> #include <string_view> int main() { std::string_view v = "Hello, world"; v = v.substr(7); std::cout << v << '\n'; } ``` Output: ``` world ``` ### See also | | | | --- | --- | | [(constructor)](basic_string_view "cpp/string/basic string view/basic string view") (C++17) | constructs a `basic_string_view` (public member function) | | [operator=](../basic_string/operator= "cpp/string/basic string/operator=") | assigns values to the string (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::rend, std::basic_string_view<CharT,Traits>::crend std::basic\_string\_view<CharT,Traits>::rend, std::basic\_string\_view<CharT,Traits>::crend =========================================================================================== | | | | | --- | --- | --- | | ``` constexpr const_reverse_iterator rend() const noexcept; ``` | | (since C++17) | | ``` constexpr const_reverse_iterator crend() const noexcept; ``` | | (since C++17) | Returns a reverse iterator to the character following the last character of the reversed view. It corresponds to the character preceding the first character of the non-reversed view. This character acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value `const_reverse_iterator` to the character following the last character. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <string_view> int main() { std::ostream_iterator<char> out_it(std::cout); std::string_view str_view("abcdef"); std::copy(str_view.rbegin(), str_view.rend(), out_it); *out_it = '\n'; std::copy(str_view.crbegin(), str_view.crend(), out_it); *out_it = '\n'; } ``` Output: ``` fedcba fedcba ``` ### See also | | | | --- | --- | | [rbegincrbegin](rbegin "cpp/string/basic string view/rbegin") (C++17) | 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::copy std::basic\_string\_view<CharT,Traits>::copy ============================================ | | | | | --- | --- | --- | | ``` size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const; ``` | | (since C++17) (until C++20) | | ``` constexpr size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const; ``` | | (since C++20) | Copies the substring `[pos, pos + rcount)` to the character array pointed to by `dest`, where `rcount` is the smaller of `count` and `size() - pos`. Equivalent to `Traits::copy(dest, data() + pos, rcount)`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the destination character string | | count | - | requested substring length | | pos | - | position of the first character | ### Return value Number of characters copied. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > size()`. ### Complexity Linear in `rcount`. ### Example ``` #include <array> #include <cstddef> #include <iostream> #include <stdexcept> #include <string_view> int main() { constexpr std::basic_string_view<char> source{"ABCDEF"}; std::array<char, 8> dest; std::size_t count{}, pos{}; dest.fill('\0'); source.copy(dest.data(), count = 4); // pos = 0 std::cout << dest.data() << '\n'; // ABCD dest.fill('\0'); source.copy(dest.data(), count = 4, pos = 1); std::cout << dest.data() << '\n'; // BCDE dest.fill('\0'); source.copy(dest.data(), count = 42, pos = 2); // ok, count -> 4 std::cout << dest.data() << '\n'; // CDEF try { source.copy(dest.data(), count = 1, pos = 666); // throws: pos > size() } catch(std::out_of_range const& ex) { std::cout << ex.what() << '\n'; } } ``` Output: ``` ABCD BCDE CDEF basic_string_view::copy: __pos (which is 666) > __size (which is 6) ``` ### See also | | | | --- | --- | | [substr](substr "cpp/string/basic string view/substr") (C++17) | returns a substring (public member function) | | [copy](../basic_string/copy "cpp/string/basic string/copy") | copies characters (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [copycopy\_if](../../algorithm/copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [memcpy](../byte/memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) |
programming_docs
cpp std::basic_string_view<CharT,Traits>::find_first_not_of std::basic\_string\_view<CharT,Traits>::find\_first\_not\_of ============================================================ | | | | | --- | --- | --- | | ``` constexpr size_type find_first_not_of( basic_string_view v, size_type pos = 0 ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr size_type find_first_not_of( CharT c, size_type pos = 0 ) const noexcept; ``` | (2) | (since C++17) | | ``` constexpr size_type find_first_not_of( const CharT* s, size_type pos, size_type count ) const; ``` | (3) | (since C++17) | | ``` constexpr size_type find_first_not_of( const CharT* s, size_type pos = 0 ) const; ``` | (4) | (since C++17) | Finds the first character not equal to any of the characters in the given character sequence. 1) Finds the first character not equal to any of the characters of `v` in this view, starting at position `pos`. 2) Equivalent to `find_first_not_of(basic_string_view([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c), 1), pos)`. 3) Equivalent to `find_first_not_of(basic_string_view(s, count), pos)`. 4) Equivalent to `find_first_not_of(basic_string_view(s), pos)`. ### Parameters | | | | | --- | --- | --- | | v | - | view to search for | | pos | - | position at which to start the search | | count | - | length of the string of characters to compare | | s | - | pointer to a string of characters to compare | | ch | - | character to compare | ### Return value Position of the first character not equal to any of the characters in the given string, or `[npos](npos "cpp/string/basic string view/npos")` if no such character is found. ### Complexity O(`size()` \* `v.size()`) at worst. ### Example ``` #include <string_view> using namespace std::literals; int main() { static_assert(2 == "BCDEF"sv.find_first_not_of("ABC")); // ^ static_assert(4 == "BCDEF"sv.find_first_not_of("ABC", 4)); // ^ static_assert(1 == "BCDEF"sv.find_first_not_of('B')); // ^ static_assert(3 == "BCDEF"sv.find_first_not_of('D', 2)); // ^ } ``` ### See also | | | | --- | --- | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [rfind](rfind "cpp/string/basic string view/rfind") (C++17) | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string view/find first of") (C++17) | find first occurrence of characters (public member function) | | [find\_last\_of](find_last_of "cpp/string/basic string view/find last of") (C++17) | find last occurrence of characters (public member function) | | [find\_last\_not\_of](find_last_not_of "cpp/string/basic string view/find last not of") (C++17) | find last absence 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::find_first_of std::basic\_string\_view<CharT,Traits>::find\_first\_of ======================================================= | | | | | --- | --- | --- | | ``` constexpr size_type find_first_of( basic_string_view v, size_type pos = 0 ) const noexcept; ``` | (1) | (since C++17) | | ``` constexpr size_type find_first_of( CharT c, size_type pos = 0 ) const noexcept; ``` | (2) | (since C++17) | | ``` constexpr size_type find_first_of( const CharT* s, size_type pos, size_type count ) const; ``` | (3) | (since C++17) | | ``` constexpr size_type find_first_of( const CharT* s, size_type pos = 0 ) const; ``` | (4) | (since C++17) | Finds the first character equal to any of the characters in the given character sequence. 1) Finds the first occurrence of any of the characters of `v` in this view, starting at position `pos`. 2) Equivalent to `find_first_of(basic_string_view([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c), 1), pos)`. 3) Equivalent to `find_first_of(basic_string_view(s, count), pos)`. 4) Equivalent to `find_first_of(basic_string_view(s), pos)`. ### Parameters | | | | | --- | --- | --- | | v | - | view to search for | | pos | - | position at which to start the search | | count | - | length of the string of characters to search for | | s | - | pointer to a string of characters to search for | | c | - | character to search for | ### Return value Position of the first occurrence of any character of the substring, or `[npos](npos "cpp/string/basic string view/npos")` if no such character is found. ### Complexity O(`size()` \* `v.size()`) at worst. ### Example ``` #include <string_view> #include <iostream> int main() { using namespace std::literals; constexpr auto N = std::string_view::npos; auto is_white_space = [](const char c) noexcept { return " \t\n\f\r\v"sv.find_first_of(c) != N; }; static_assert( 1 == "alignas"sv.find_first_of("klmn"sv) && // └─────────────────────────┘ N == "alignof"sv.find_first_of("wxyz"sv) && // 3 == "concept"sv.find_first_of("bcde"sv, /* pos= */ 1) && // └───────────────────────┘ N == "consteval"sv.find_first_of("oxyz"sv, /* pos= */ 2) && // 6 == "constexpr"sv.find_first_of('x') && // └─────────────────────┘ N == "constinit"sv.find_first_of('x') && // 6 == "const_cast"sv.find_first_of('c', /* pos= */ 4) && // └──────────────────────┘ N == "continue"sv.find_first_of('c', /* pos= */ 42) && // 5 == "co_await"sv.find_first_of("cba", /* pos= */ 4) && // └───────────────────────┘ 7 == "decltype"sv.find_first_of("def", /* pos= */ 2, /* count= */ 2) && // └────────────────────┘ N == "decltype"sv.find_first_of("def", /* pos= */ 2, /* count= */ 1) && // is_white_space(' ') && is_white_space('\r') && !is_white_space('\a') ); std::cout << "All tests passed.\n"; } ``` Output: ``` All tests passed. ``` ### See also | | | | --- | --- | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [rfind](rfind "cpp/string/basic string view/rfind") (C++17) | find the last occurrence of a substring (public member function) | | [find\_last\_of](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](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](find_last_not_of "cpp/string/basic string view/find last not of") (C++17) | find last absence of characters (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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::substr std::basic\_string\_view<CharT,Traits>::substr ============================================== | | | | | --- | --- | --- | | ``` constexpr basic_string_view substr( size_type pos = 0, size_type count = npos ) const; ``` | | (since C++17) | Returns a view of the substring `[pos, pos + *rcount*)`, where `*rcount*` is the smaller of `count` and `size() - pos`. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the first character | | count | - | requested length | ### Return value View of the substring `[pos, pos + *rcount*)`. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > size()`. ### Complexity Constant. ### Example ``` #include <cstddef> #include <iostream> #include <stdexcept> #include <string_view> int main() { typedef std::size_t count_t, pos_t; constexpr std::string_view data{"ABCDEF"}; std::cout << data.substr() << '\n'; // ABCDEF std::cout << data.substr(pos_t(1)) << '\n'; // BCDEF std::cout << data.substr(pos_t(2), count_t(3)) << '\n'; // CDE std::cout << data.substr(pos_t(4), count_t(42)) << '\n'; // EF // count -> 2 == size() - pos == 6 - 4 try { data.substr(pos_t(666), count_t(1)); // throws: pos > size() } catch(std::out_of_range const& ex) { std::cout << ex.what() << '\n'; } } ``` Possible output: ``` ABCDEF BCDEF CDE EF basic_string_view::substr: __pos (which is 666) > __size (which is 6) ``` ### See also | | | | --- | --- | | [copy](copy "cpp/string/basic string view/copy") (C++17) | copies characters (public member function) | | [find](find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function) | | [substr](../basic_string/substr "cpp/string/basic string/substr") | returns a substring (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp operator==,!=,<,<=,>,>=,<=>(std::basic_string_view) operator==,!=,<,<=,>,>=,<=>(std::basic\_string\_view) ===================================================== | Defined in header `[<string\_view>](../../header/string_view "cpp/header/string view")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > constexpr bool operator==( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (1) | (since C++17) | | ``` template< class CharT, class Traits > constexpr bool operator!=( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (2) | (since C++17) (until C++20) | | ``` template< class CharT, class Traits > constexpr bool operator<( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (3) | (since C++17) (until C++20) | | ``` template< class CharT, class Traits > constexpr bool operator<=( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (4) | (since C++17) (until C++20) | | ``` template< class CharT, class Traits > constexpr bool operator>( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (5) | (since C++17) (until C++20) | | ``` template< class CharT, class Traits > constexpr bool operator>=( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (6) | (since C++17) (until C++20) | | ``` template< class CharT, class Traits > constexpr /*comp-cat*/ operator<=>( std::basic_string_view<CharT,Traits> lhs, std::basic_string_view<CharT,Traits> rhs ) noexcept; ``` | (7) | (since C++20) | Compares two views. All comparisons are done via the `[compare()](compare "cpp/string/basic string view/compare")` member function (which itself is defined in terms of `Traits::compare()`): * Two views are equal if both the size of `lhs` and `rhs` are equal and each character in `lhs` has an equivalent character in `rhs` at the same position. * The ordering comparisons are done lexicographically -- the comparison is performed by a function equivalent to `[std::lexicographical\_compare](../../algorithm/lexicographical_compare "cpp/algorithm/lexicographical compare")`. | | | | --- | --- | | The return type of three-way comparison operators (`/*comp-cat*/`) is `Traits::comparison_category` if that qualified-id denotes a type, `std::weak_ordering` otherwise. If `/*comp-cat*/` is not a comparison category type, the program is ill-formed. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | The implementation shall provide sufficient additional `constexpr` and `noexcept` overloads of these functions so that a `basic_string_view<CharT,Traits>` object `sv` may be compared to another object `t` with an implicit conversion to `basic_string_view<CharT,Traits>`, with semantics identical to comparing `sv` and `basic_string_view<CharT,Traits>(t)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | views to compare | ### Return value 1-6) `true` if the corresponding comparison holds, `false` otherwise. 7) `static_cast</*comp-cat*/>(lhs.compare(rhs) <=> 0)`. ### Complexity Linear in the size of the views. ### Notes Sufficient additional overloads can be implemented through non-deduced context in one parameter type. | | | | --- | --- | | Three-way comparison result type of `[std::string\_view](../basic_string_view "cpp/string/basic string view")`, `[std::wstring\_view](../basic_string_view "cpp/string/basic string view")`, `[std::u8string\_view](../basic_string_view "cpp/string/basic string view")`, `[std::u16string\_view](../basic_string_view "cpp/string/basic string view")` and `[std::u32string\_view](../basic_string_view "cpp/string/basic string view")` is `std::strong_ordering`. | (since C++20) | ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3432](https://cplusplus.github.io/LWG/issue3432) | C++20 | the return type of `operator<=>` was not required to be a comparison category type | required | cpp std::basic_string_view<CharT,Traits>::empty std::basic\_string\_view<CharT,Traits>::empty ============================================= | | | | | --- | --- | --- | | ``` constexpr bool empty() const noexcept; ``` | | (since C++17) (until C++20) | | ``` [[nodiscard]] constexpr bool empty() const noexcept; ``` | | (since C++20) | Checks if the view has no characters, i.e. whether `size() == 0`. ### Parameters (none). ### Return value `true` if the view is empty, `false` otherwise. ### Complexity Constant. ### Example ``` #include <string_view> #include <iostream> void check_string(std::string_view ref) { // Print a string surrounded by single quotes, its length // and whether it is considered empty. std::cout << std::boolalpha << "'" << ref << "' has " << ref.size() << " character(s); emptiness: " << ref.empty() << '\n'; } int main(int argc, char **argv) { // An empty string check_string(""); // Almost always not empty: argv[0] if (argc > 0) check_string(argv[0]); } ``` Possible output: ``` '' has 0 character(s); emptiness: true './a.out' has 7 character(s); emptiness: false ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string view/size") (C++17) | returns the number of characters (public member function) | | [max\_size](max_size "cpp/string/basic string view/max size") (C++17) | returns the maximum number of characters (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [empty](../basic_string/empty "cpp/string/basic string/empty") | checks whether the string is empty (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::begin, std::basic_string_view<CharT,Traits>::cbegin std::basic\_string\_view<CharT,Traits>::begin, std::basic\_string\_view<CharT,Traits>::cbegin ============================================================================================= | | | | | --- | --- | --- | | ``` constexpr const_iterator begin() const noexcept; ``` | | (since C++17) | | ``` constexpr const_iterator cbegin() const noexcept; ``` | | (since C++17) | Returns an iterator to the first character of the view. ![range-begin-end.svg]() ### Parameters (none). ### Return value `const_iterator` to the first character. ### Complexity Constant. ### Example ``` #include <iostream> #include <string_view> #include <type_traits> int main() { std::string_view str_view("abcd"); auto begin = str_view.begin(); auto cbegin = str_view.cbegin(); std::cout << *begin << '\n'; std::cout << *cbegin << '\n'; std::cout << std::boolalpha << (begin == cbegin) << '\n'; std::cout << std::boolalpha << (*begin == *cbegin) << '\n'; static_assert(std::is_same<decltype(begin), decltype(cbegin)>{}); } ``` Output: ``` a a true true ``` ### See also | | | | --- | --- | | [endcend](end "cpp/string/basic string view/end") (C++17) | returns an iterator to the end (public member function) | | [begincbegin](../basic_string/begin "cpp/string/basic string/begin") (C++11) | returns an iterator to the beginning (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::basic_string_view<CharT,Traits>::basic_string_view std::basic\_string\_view<CharT,Traits>::basic\_string\_view =========================================================== | | | | | --- | --- | --- | | ``` constexpr basic_string_view() noexcept; ``` | (1) | (since C++17) | | ``` constexpr basic_string_view( const basic_string_view& other ) noexcept = default; ``` | (2) | (since C++17) | | ``` constexpr basic_string_view( const CharT* s, size_type count ); ``` | (3) | (since C++17) | | ``` constexpr basic_string_view( const CharT* s ); ``` | (4) | (since C++17) | | ``` template< class It, class End > constexpr basic_string_view( It first, End last ); ``` | (5) | (since C++20) | | ``` template< class R > explicit constexpr basic_string_view( R&& r ); ``` | (6) | (since C++23) | | ``` constexpr basic_string_view( std::nullptr_t ) = delete; ``` | (7) | (since C++23) | 1) Default constructor. Constructs an empty `basic_string_view`. After construction, `[data()](data "cpp/string/basic string view/data")` is equal to `nullptr`, and `[size()](size "cpp/string/basic string view/size")` is equal to `​0​`. 2) Copy constructor. Constructs a view of the same content as `other`. After construction, `[data()](data "cpp/string/basic string view/data")` is equal to `other.data()`, and `[size()](size "cpp/string/basic string view/size")` is equal to `other.size()`. 3) Constructs a view of the first `count` characters of the character array starting with the element pointed by `s`. `s` can contain null characters. The behavior is undefined if `[s, s+count)` is not a valid range (even though the constructor may not access any of the elements of this range). After construction, `[data()](data "cpp/string/basic string view/data")` is equal to `s`, and `[size()](size "cpp/string/basic string view/size")` is equal to `count`. 4) Constructs a view of the null-terminated character string pointed to by `s`, not including the terminating null character. The length of the view is determined as if by `Traits::length(s)`. The behavior is undefined if `[s, s+Traits::length(s))` is not a valid range. After construction, `[data()](data "cpp/string/basic string view/data")` is equal to `s`, and `[size()](size "cpp/string/basic string view/size")` is equal to `Traits::length(s)`. 5) Constructs a `basic_string_view` over the range `[first, last)`. The behavior is undefined if `[first, last)` is not a valid range, if `It` does not actually model [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), or if `End` does not actually model [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") for `It`. After construction, `[data()](data "cpp/string/basic string view/data")` is equal to `[std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(first)`, and `[size()](size "cpp/string/basic string view/size")` is equal to `(last - first)`. This overload participates in overload resolution only if. * `It` satisfies [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), * `End` satisfies [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") for `It`, * `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<It>` and `CharT` are the same type, and * `End` is not convertible to `[std::size\_t](../../types/size_t "cpp/types/size t")`. 6) Constructs a `basic_string_view` over the range `r`. After construction, `[data()](data "cpp/string/basic string view/data")` is equal to `[ranges::data](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/data)(r)`, and `[size()](size "cpp/string/basic string view/size")` is equal to `[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(r)`. This overload participates in overload resolution only if. * `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<R>` is not the same type as `basic_string_view`, * `R` models [`contiguous_range`](../../ranges/contiguous_range "cpp/ranges/contiguous range") and [`sized_range`](../../ranges/sized_range "cpp/ranges/sized range"), * `[ranges::range\_value\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<R>` and `CharT` are the same type, * `R` is not convertible to `const CharT*`, * let `d` be an lvalue of type `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<R>`, `d.operator ::[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>()` is not a valid expression, and * if qualified-id `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<R>::traits\_type` is valid and denotes a type, it is same as `Traits`. 7) `basic_string_view` cannot be constructed from `nullptr`. ### Parameters | | | | | --- | --- | --- | | other | - | another view to initialize the view with | | s | - | pointer to a character array or a C string to initialize the view with | | count | - | number of characters to include in the view | | first | - | iterator to the first character of the sequence | | last | - | iterator past the last character of the sequence or another sentinel | | r | - | a contiguous range that contains the sequence | ### Complexity 1-3,5-6) constant 4) linear in length of `s` ### Example ``` #include <array> #include <iomanip> #include <iostream> #include <string> #include <string_view> int main() { std::string cppstr = "Foo"; std::string_view cppstr_v(cppstr); // overload (2), after // std::string::operator string_view std::cout << "1) cppstr_v: " << quoted( cppstr_v ) << '\n'; char array[3] = {'B', 'a', 'r'}; std::string_view array_v(array, std::size(array)); // overload (3) std::cout << "2) array_v: " << quoted( array_v ) << '\n'; const char* one_0_two = "One\0Two"; std::string_view one_two_v {one_0_two, 7}; // overload (3) std::cout << "3) one_two_v: \""; for (char c: one_two_v) { std::cout << (c != '\0' ? c : '?'); } std::cout << "\", one_two_v.size(): " << one_two_v.size() << '\n'; std::string_view one_v {one_0_two}; // overload (4) std::cout << "4) one_v: " << quoted( one_v ) << ", one_v.size(): " << one_v.size() << '\n'; constexpr std::wstring_view wcstr_v = L"xyzzy"; // overload (4) std::cout << "5) wcstr_v.size(): " << wcstr_v.size() << '\n'; std::array ar = {'P', 'u', 'b'}; std::string_view ar_v(ar.begin(), ar.end()); // overload (5), C++20 std::cout << "6) ar_v: " << quoted( ar_v ) << '\n'; // std::string_view ar_v2{ar}; // overload (6), OK in C++23 // std::cout << "ar_v2: " << quoted( ar_v2 ) << '\n'; // ar_v2: "Pub" [[maybe_unused]] auto zero = [] { /* ... */ return nullptr; }; // std::string_view s{ zero() }; // overload (7), won't compile since C++23 } ``` Output: ``` 1) cppstr_v: "Foo" 2) array_v: "Bar" 3) one_two_v: "One?Two", one_two_v.size(): 7 4) one_v: "One", one_v.size(): 3 5) wcstr_v.size(): 5 6) ar_v: "Pub" ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/string/basic string view/operator=") (C++17) | assigns a view (public member function) | | [(constructor)](../basic_string/basic_string "cpp/string/basic string/basic string") | constructs a `basic_string` (public member function of `std::basic_string<CharT,Traits,Allocator>`) |
programming_docs
cpp std::basic_string_view<CharT,Traits>::end, std::basic_string_view<CharT,Traits>::cend std::basic\_string\_view<CharT,Traits>::end, std::basic\_string\_view<CharT,Traits>::cend ========================================================================================= | | | | | --- | --- | --- | | ``` constexpr const_iterator end() const noexcept; ``` | | (since C++17) | | ``` constexpr const_iterator cend() const noexcept; ``` | | (since C++17) | Returns an iterator to the character following the last character of the view. This character acts as a placeholder, attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value `const_iterator` to the character following the last character. ### Complexity Constant. ### Example ``` #include <iostream> #include <iterator> #include <string_view> int main() { std::string_view str_view("abcd"); auto end = str_view.end(); auto cend = str_view.cend(); std::cout << *std::prev(end) << '\n'; std::cout << *std::prev(cend) << '\n'; std::cout << std::boolalpha << (end == cend) << '\n'; } ``` Output: ``` d d true ``` ### See also | | | | --- | --- | | [begincbegin](begin "cpp/string/basic string view/begin") (C++17) | 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 of `std::basic_string<CharT,Traits,Allocator>`) | cpp operator<<,>>(std::basic_string) operator<<,>>(std::basic\_string) ================================= | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Allocator > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::basic_string<CharT, Traits, Allocator>& str ); ``` | (1) | | | ``` template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, std::basic_string<CharT, Traits, Allocator>& str ); ``` | (2) | | 1) Behaves as a [FormattedOutputFunction](../../named_req/formattedoutputfunction "cpp/named req/FormattedOutputFunction"). After constructing and checking the sentry object, determines the output format padding as follows: * If `str.size()` is not less than `os.width()`, uses the range `[str.begin(), str.end())` as-is. * Otherwise, if `(os.flags() & ios_base::adjustfield) == ios_base::left`, places `os.width() - str.size()` copies of the `os.fill()` character after the character sequence. * Otherwise, places `os.width() - str.size()` copies of the `os.fill()` character before the character sequence. Then stores each character from the resulting sequence (the contents of `str` plus padding) to the output stream `os` as if by calling `os.rdbuf()->sputn(seq, n)`, where `n` is `[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(os.width(), str.size())`. Finally, calls `os.width(0)` to cancel the effects of `[std::setw](../../io/manip/setw "cpp/io/manip/setw")`, if any. 2) Behaves as a [FormattedInputFunction](../../named_req/formattedinputfunction "cpp/named req/FormattedInputFunction"). After constructing and checking the sentry object, which may skip leading whitespace, first clears `str` with `str.erase()`, then reads characters from `is` and appends them to `str` as if by `str.append(1, c)`, until one of the following conditions becomes true: * `N` characters are read, where `N` is `is.width()` if `is.width() > 0`, otherwise `N` is `str.max_size()`, * the end-of-file condition occurs in the stream `is`, or * `std::isspace(c, is.getloc())` is true for the next character `c` in `is` (this whitespace character remains in the input stream). If no characters are extracted then `std::ios::failbit` is set on `is`, which may throw `[std::ios\_base::failure](../../io/ios_base/failure "cpp/io/ios base/failure")`. Finally, calls `is.width(0)` to cancel the effects of `[std::setw](../../io/manip/setw "cpp/io/manip/setw")`, if any. ### Exceptions 1) may throw `[std::ios\_base::failure](../../io/ios_base/failure "cpp/io/ios base/failure")` if an exception is thrown during output. 2) may throw `[std::ios\_base::failure](../../io/ios_base/failure "cpp/io/ios base/failure")` if no characters are extracted from `is` (e.g the stream is at end of file, or consists of whitespace only), or if an exception is thrown during input. ### Parameters | | | | | --- | --- | --- | | os | - | a character output stream | | is | - | a character input stream | | str | - | the string to be inserted or extracted | ### Return value 1) `os` 2) `is` ### Example ``` #include <iostream> #include <string> #include <sstream> int main() { std::string greeting = "Hello, whirled!"; std::istringstream iss(greeting); std::string hello_comma, whirled, word; iss >> hello_comma; iss >> whirled; std::cout << greeting << '\n' << hello_comma << '\n' << whirled << '\n'; // Reset the stream iss.clear(); iss.seekg(0); while (iss >> word) std::cout << '+' << word << '\n'; } ``` Output: ``` Hello, whirled! Hello, whirled! +Hello, +whirled! ``` ### 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 25](https://cplusplus.github.io/LWG/issue25) | C++98 | `n` was the smaller of `os.width()` and `str.size()` | `n` is the larger of them | | [LWG 90](https://cplusplus.github.io/LWG/issue90) | C++98 | `std::isspace(c, getloc())` was used to checkfor spaces, but `getloc` is not declared in [`<string>`](../../header/string "cpp/header/string") | replaced with`std::isspace(c, is.getloc())` | | [LWG 91](https://cplusplus.github.io/LWG/issue91) | C++98 | `operator>>` did not behaveas a formatted input function | behaves as a formattedinput function | ### See also | | | | --- | --- | | [operator<<](../basic_string_view/operator_ltlt "cpp/string/basic string view/operator ltlt") (C++17) | performs stream output on string views (function template) | cpp std::stoul, std::stoull std::stoul, std::stoull ======================= | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` unsigned long stoul( const std::string& str, std::size_t* pos = nullptr, int base = 10 ); unsigned long stoul( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 ); ``` | (1) | (since C++11) | | ``` unsigned long long stoull( const std::string& str, std::size_t* pos = nullptr, int base = 10 ); unsigned long long stoull( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 ); ``` | (2) | (since C++11) | Interprets an unsigned integer value in the string `str`. 1) calls `[std::strtoul](http://en.cppreference.com/w/cpp/string/byte/strtoul)(str.c\_str(), &ptr, base)` or `[std::wcstoul](http://en.cppreference.com/w/cpp/string/wide/wcstoul)(str.c\_str(), &ptr, base)` 2) calls `[std::strtoull](http://en.cppreference.com/w/cpp/string/byte/strtoul)(str.c\_str(), &ptr, base)` or `[std::wcstoull](http://en.cppreference.com/w/cpp/string/wide/wcstoul)(str.c\_str(), &ptr, base)` Discards any whitespace characters (as identified by calling [`std::isspace`](../byte/isspace "cpp/string/byte/isspace")) 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. If `pos` is not a null pointer, then a pointer `ptr`, internal to the conversion functions, will receive the address of the first unconverted character in `str.c_str()`, and the index of that character will be calculated and stored in `*pos`, giving the number of characters that were processed by the conversion. ### Parameters | | | | | --- | --- | --- | | str | - | the string to convert | | pos | - | address of an integer to store the number of characters processed | | base | - | the number base | ### Return value The string converted to the specified unsigned integer type. ### Exceptions * `[std::invalid\_argument](../../error/invalid_argument "cpp/error/invalid argument")` if no conversion could be performed * `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if the converted value would fall out of the range of the result type or if the underlying function (std::strtoul or std::strtoull) sets `errno` to `[ERANGE](http://en.cppreference.com/w/cpp/error/errno_macros)`. ### See also | | | | --- | --- | | [stoistolstoll](stol "cpp/string/basic string/stol") (C++11)(C++11)(C++11) | converts a string to a signed integer (function) | | [stofstodstold](stof "cpp/string/basic string/stof") (C++11)(C++11)(C++11) | converts a string to a floating point value (function) | cpp std::basic_string<CharT,Traits,Allocator>::compare std::basic\_string<CharT,Traits,Allocator>::compare =================================================== | | | | | --- | --- | --- | | | (1) | | | ``` int compare( const basic_string& str ) const; ``` | (until C++11) | | ``` int compare( const basic_string& str ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr int compare( const basic_string& str ) const noexcept; ``` | (since C++20) | | | (2) | | | ``` int compare( size_type pos1, size_type count1, const basic_string& str ) const; ``` | (until C++20) | | ``` constexpr int compare( size_type pos1, size_type count1, const basic_string& str ) const; ``` | (since C++20) | | | (3) | | | ``` int compare( size_type pos1, size_type count1, const basic_string& str, size_type pos2, size_type count2 ) const; ``` | (until C++14) | | ``` int compare( size_type pos1, size_type count1, const basic_string& str, size_type pos2, size_type count2 = npos ) const; ``` | (since C++14) (until C++20) | | ``` constexpr int compare( size_type pos1, size_type count1, const basic_string& str, size_type pos2, size_type count2 = npos ) const; ``` | (since C++20) | | | (4) | | | ``` int compare( const CharT* s ) const; ``` | (until C++20) | | ``` constexpr int compare( const CharT* s ) const; ``` | (since C++20) | | | (5) | | | ``` int compare( size_type pos1, size_type count1, const CharT* s ) const; ``` | (until C++20) | | ``` constexpr int compare( size_type pos1, size_type count1, const CharT* s ) const; ``` | (since C++20) | | | (6) | | | ``` int compare( size_type pos1, size_type count1, const CharT* s, size_type count2 ) const; ``` | (until C++20) | | ``` constexpr int compare( size_type pos1, size_type count1, const CharT* s, size_type count2 ) const; ``` | (since C++20) | | | (7) | | | ``` template < class StringViewLike > int compare( const StringViewLike& t ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr int compare( const StringViewLike& t ) const noexcept(/* see below */); ``` | (since C++20) | | | (8) | | | ``` template < class StringViewLike > int compare( size_type pos1, size_type count1, const StringViewLike& t ) const; ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr int compare( size_type pos1, size_type count1, const StringViewLike& t ) const; ``` | (since C++20) | | | (9) | | | ``` template < class StringViewLike > int compare( size_type pos1, size_type count1, const StringViewLike& t, size_type pos2, size_type count2 = npos) const; ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr int compare( size_type pos1, size_type count1, const StringViewLike& t, size_type pos2, size_type count2 = npos) const; ``` | (since C++20) | Compares two character sequences. 1) Compares this string to *str*. 2) Compares a `[pos1, pos1+count1)` substring of this string to *str*. If `count1 > size() - pos1` the substring is `[pos1, size())`. 3) Compares a `[pos1, pos1+count1)` substring of this string to a substring `[pos2, pos2+count2)` of *str*. If `count1 > size() - pos1` the first substring is `[pos1, size())`. Likewise, `count2 > str.size() - pos2` the second substring is `[pos2, str.size())`. 4) Compares this string to the null-terminated character sequence beginning at the character pointed to by *s* with length `Traits::length(s)`. 5) Compares a `[pos1, pos1+count1)` substring of this string to the null-terminated character sequence beginning at the character pointed to by *s* with length `Traits::length(s)`. If `count1 > size() - pos1` the substring is `[pos1, size())`. 6) Compares a `[pos1, pos1+count1)` substring of this string to the characters in the range `[s, s + count2)`. If `count1 > size() - pos1` the substring is `[pos1, size())`. (Note: the characters in the range `[s, s + count2)` may include null characters.) 7) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then compares this string to `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 8) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then compares a `[pos1, pos1+count1)` substring of this string to `sv`, as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>(\*this).substr(pos1, count1).compare(sv)`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 9) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then compares a `[pos1, pos1+count1)` substring of this string to a substring `[pos2, pos2+count2)` of `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>(\*this).substr(pos1, count1).compare(sv.substr(pos2, count2))`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. A character sequence consisting of `count1` characters starting at `data1` is compared to a character sequence consisting of `count2` characters starting at `data2` as follows. First, calculate the number of characters to compare, as if by `size_type rlen = [std::min](http://en.cppreference.com/w/cpp/algorithm/min)(count1, count2)`. Then compare the sequences by calling `Traits::compare(data1, data2, rlen)`. For standard strings this function performs character-by-character lexicographical comparison. If the result is zero (the character sequences are equal so far), then their sizes are compared as follows: | Condition | Result | Return value | | --- | --- | --- | | `Traits::compare(data1, data2, rlen) < 0` | data1 is *less* than data2 | `<0` | | `Traits::compare(data1, data2, rlen) == 0` | size1 < size2 | data1 is *less* than data2 | `<0` | | size1 == size2 | data1 is *equal* to data2 | `​0​` | | size1 > size2 | data1 is *greater* than data2 | `>0` | | `Traits::compare(data1, data2, rlen) > 0` | data1 is *greater* than data2 | `>0` | ### Parameters | | | | | --- | --- | --- | | str | - | other string to compare to | | s | - | pointer to the character string to compare to | | count1 | - | number of characters of this string to compare | | pos1 | - | position of the first character in this string to compare | | count2 | - | number of characters of the given string to compare | | pos2 | - | position of the first character of the given string to compare | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) to compare to | ### Return value * negative value if `*this` appears before the character sequence specified by the arguments, in lexicographical order * zero if both character sequences compare equivalent * positive value if `*this` appears after the character sequence specified by the arguments, in lexicographical order ### Exceptions The overloads taking parameters named `pos1` or `pos2` throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if the argument is out of range. 7) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>)` 8-9) Throws anything thrown by the conversion to `basic_string_view`. ### Possible implementation | | | --- | | ``` template<class CharT, class Traits, class Alloc> int basic_string<CharT, Traits, Alloc>::compare(const std::basic_string& s) const noexcept { size_type lhs_sz = size(); size_type rhs_sz = s.size(); int result = traits_type::compare(data(), s.data(), std::min(lhs_sz, rhs_sz)); if (result != 0) return result; if (lhs_sz < rhs_sz) return -1; if (lhs_sz > rhs_sz) return 1; return 0; } ``` | ### Notes For the situations when three-way comparison is not required, `[std::basic\_string](../basic_string "cpp/string/basic string")` provides the usual [relational operators](operator_cmp "cpp/string/basic string/operator cmp") (`<`, `<=`, `==`, `>`, etc). By default (with the default `[std::char\_traits](../char_traits "cpp/string/char traits")`), this function is not locale-sensitive. See `[std::collate::compare](../../locale/collate/compare "cpp/locale/collate/compare")` for locale-aware three-way string comparison. ### Example ``` #include <cassert> #include <string> #include <iostream> int main() { std::string batman{"Batman"}; std::string superman{"Superman"}; int compare_result{0}; // 1) Compare with other string compare_result = batman.compare(superman); std::cout << "1) " << ( compare_result < 0 ? "Batman comes before Superman.\n" : compare_result > 0 ? "Superman comes before Batman.\n" : "Superman and Batman are the same.\n" ); // 2) Compare substring with other string compare_result = batman.compare(3, 3, superman); std::cout << "2) " << ( compare_result < 0 ? "man comes before Superman.\n" : compare_result > 0 ? "Superman comes before man.\n" : "man and Superman are the same.\n" ); // 3) Compare substring with other substring compare_result = batman.compare(3, 3, superman, 5, 3); std::cout << "3) " << ( compare_result < 0 ? "man comes before man.\n" : compare_result > 0 ? "man comes before man.\n" : "man and man are the same.\n" ); // Compare substring with other substring // defaulting to end of other string assert(compare_result == batman.compare(3, 3, superman, 5)); // 4) Compare with char pointer compare_result = batman.compare("Superman"); std::cout << "4) " << ( compare_result < 0 ? "Batman comes before Superman.\n" : compare_result > 0 ? "Superman comes before Batman.\n" : "Superman and Batman are the same.\n" ); // 5) Compare substring with char pointer compare_result = batman.compare(3, 3, "Superman"); std::cout << "5) " << ( compare_result < 0 ? "man comes before Superman.\n" : compare_result > 0 ? "Superman comes before man.\n" : "man and Superman are the same.\n" ); // 6) Compare substring with char pointer substring compare_result = batman.compare(0, 3, "Superman", 5); std::cout << "6) " << ( compare_result < 0 ? "Bat comes before Super.\n" : compare_result > 0 ? "Super comes before Bat.\n" : "Super and Bat are the same.\n" ); } ``` Output: ``` 1) Batman comes before Superman. 2) Superman comes before man. 3) man and man are the same. 4) Batman comes before Superman. 5) Superman comes before man. 6) Bat comes before Super. ``` ### 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 5](https://cplusplus.github.io/LWG/issue5) | C++98 | the parameter `count2` of overload (6)had a default argument `npos` | default argument removed,split to overloads (5) and (6) | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++17 | noexcept for overload (7) was accidentlydropped by the resolution of LWG2946 | restored | ### See also | | | | --- | --- | | [operator==operator!=operator<operator>operator<=operator>=operator<=>](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) | | [substr](substr "cpp/string/basic string/substr") | returns a substring (public member function) | | [collate](../../locale/collate "cpp/locale/collate") | defines lexicographical comparison and hashing of strings (class template) | | [strcoll](../byte/strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) | | [lexicographical\_compare](../../algorithm/lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [compare](../basic_string_view/compare "cpp/string/basic string view/compare") (C++17) | compares two views (public member function of `std::basic_string_view<CharT,Traits>`) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::contains std::basic\_string<CharT,Traits,Allocator>::contains ==================================================== | | | | | --- | --- | --- | | ``` constexpr bool contains( std::basic_string_view<CharT,Traits> sv ) const noexcept; ``` | (1) | (since C++23) | | ``` constexpr bool contains( CharT c ) const noexcept; ``` | (2) | (since C++23) | | ``` constexpr bool contains( const CharT* s ) const; ``` | (3) | (since C++23) | Checks if the string contains the given substring. The substring may be one of the following: 1) a string view `sv` (which may be a result of implicit conversion from another `std::basic_string`). 2) a single character `c`. 3) a null-terminated character string `s`. All three overloads are equivalent to `return find(x) != npos;`, where `x` is the parameter. ### Parameters | | | | | --- | --- | --- | | sv | - | a string view which may be a result of implicit conversion from another `std::basic_string` | | c | - | a single character | | s | - | a null-terminated character string | ### Return value `true` if the string contains the provided substring, `false` otherwise. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_string_contains`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iomanip> #include <iostream> #include <string> #include <string_view> #include <type_traits> template <typename SubstrType> void test_substring(const std::string& str, SubstrType subs) { constexpr char delim = std::is_scalar_v<SubstrType> ? '\'' : '\"'; std::cout << std::quoted(str) << (str.contains(subs) ? " contains " : " does not contain ") << std::quoted(std::string{subs}, delim) << '\n'; } int main() { using namespace std::literals; auto helloWorld = "hello world"s; test_substring(helloWorld, "hello"sv); test_substring(helloWorld, "goodbye"sv); test_substring(helloWorld, 'w'); test_substring(helloWorld, 'x'); } ``` Output: ``` "hello world" contains "hello" "hello world" does not contain "goodbye" "hello world" contains 'w' "hello world" does not contain 'x' ``` ### See also | | | | --- | --- | | [starts\_with](starts_with "cpp/string/basic string/starts with") (C++20) | checks if the string starts with the given prefix (public member function) | | [ends\_with](ends_with "cpp/string/basic string/ends with") (C++20) | checks if the string ends with the given suffix (public member function) | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [substr](substr "cpp/string/basic string/substr") | returns a substring (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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length std::basic\_string<CharT,Traits,Allocator>::size, std::basic\_string<CharT,Traits,Allocator>::length ==================================================================================================== | | | | | --- | --- | --- | | ``` 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) | | ``` size_type length() const; ``` | | (until C++11) | | ``` size_type length() const noexcept; ``` | | (since C++11) (until C++20) | | ``` constexpr size_type length() const noexcept; ``` | | (since C++20) | Returns the number of `CharT` elements in the string, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of `CharT` elements in the string. ### Complexity | | | | --- | --- | | Unspecified. | (until C++11) | | Constant. | (since C++11) | ### Notes For `[std::string](../basic_string "cpp/string/basic string")`, the elements are bytes (objects of type char), which are not the same as characters if a multibyte encoding such as UTF-8 is used. ### Example ``` #include <cassert> #include <iterator> #include <string> int main() { std::string s("Exemplar"); assert(8 == s.size()); assert(s.size() == s.length()); assert(s.size() == static_cast<std::string::size_type>( std::distance(s.begin(), s.end()))); std::u32string a(U"ハロー・ワールド"); // 8 code points assert(8 == a.size()); // 8 code units in UTF-32 std::u16string b(u"ハロー・ワールド"); // 8 code points assert(8 == b.size()); // 8 code units in UTF-16 std::string c("ハロー・ワールド"); // 8 code points assert(24 == c.size()); // 24 code units in UTF-8 #if __cplusplus >= 202002 std::u8string d(u8"ハロー・ワールド"); // 8 code points assert(24 == d.size()); // 24 code units in UTF-8 #endif } ``` ### See also | | | | --- | --- | | [empty](empty "cpp/string/basic string/empty") | checks whether the string is empty (public member function) | | [max\_size](max_size "cpp/string/basic string/max size") | returns the maximum number of characters (public member function) | | [sizelength](../basic_string_view/size "cpp/string/basic string view/size") (C++17) | returns the number of characters (public member function of `std::basic_string_view<CharT,Traits>`) | cpp deduction guides for std::basic_string deduction guides for `std::basic_string` ======================================== | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` template< class InputIt, class Alloc = std::allocator< typename std::iterator_traits<InputIt>::value_type> > basic_string( InputIt, InputIt, Alloc = Alloc() ) -> basic_string<typename std::iterator_traits<InputIt>::value_type, std::char_traits<typename std::iterator_traits<InputIt>::value_type>, Alloc>; ``` | (1) | (since C++17) | | ``` template< class CharT, class Traits, class Alloc = std::allocator<CharT> > explicit basic_string( std::basic_string_view<CharT, Traits>, const Alloc& = Alloc() ) -> basic_string<CharT, Traits, Alloc>; ``` | (2) | (since C++17) | | ``` template< class CharT, class Traits, class Alloc = std::allocator<CharT>> > basic_string( std::basic_string_view<CharT, Traits>, typename /*see below*/::size_type, typename /*see below*/::size_type, const Alloc& = Alloc() ) -> basic_string<CharT, Traits, Alloc>; ``` | (3) | (since C++17) | 1) This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::basic\_string](../basic_string "cpp/string/basic string")` 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"). 2-3) These deduction guides are provided for `[std::basic\_string](../basic_string "cpp/string/basic string")` to allow deduction from a `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`. The `size_type` parameter type in (3) refers to the `size_type` member type of the type deduced by the deduction guide. These overloads participate in overload resolution only if `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. ### Notes Guides (2-3) are needed because the `[std::basic\_string](../basic_string "cpp/string/basic string")` constructors for `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`s are made templates to avoid causing ambiguities in existing code, and those templates do not support class template argument deduction. ### Example ``` #include <string> #include <vector> int main() { std::vector<char> v = {'a', 'b', 'c'}; std::basic_string s(v.begin(), v.end()); // uses explicit deduction guide } ``` ### 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 3075](https://cplusplus.github.io/LWG/issue3075) | C++17 | deduction from `basic_string_view` was unsupported (exacerbated by [LWG issue 2946](https://cplusplus.github.io/LWG/issue2946)) | deduction guides added | cpp std::basic_string<CharT,Traits,Allocator>::resize_and_overwrite std::basic\_string<CharT,Traits,Allocator>::resize\_and\_overwrite ================================================================== | | | | | --- | --- | --- | | ``` template< class Operation > constexpr void resize_and_overwrite( size_type count, Operation op ); ``` | | (since C++23) | Resizes the string to contain at most `count` characters, using the user-provided operation `op` to modify the possibly indeterminate contents and set the length. This avoids the cost of initializing a suitably-sized `[std::string](../basic_string "cpp/string/basic string")` when it is intended to be used as a char array to be populated by, e.g., a C API call. This function performs following steps: 1. Obtains a contiguous storage that contains `count + 1` characters, and makes its first `k` characters equal to the first `k` characters of `*this`, where `k` is the smaller of `count` and the result of `this->[size()](size "cpp/string/basic string/size")` before the call to `resize_and_overwrite`. Let `p` denote the pointer to the first character in the storage. * The equality is determined as if by checking `this->[compare](compare "cpp/string/basic string/compare")(0, k, p, k) == 0`. * The characters in `[p + k, p + count]` may have indeterminate values. 2. Evaluates `[std::move](../../utility/move "cpp/utility/move")(op)(p, count)`. Let `r` be the return value of `std::move(op)(p, count)`. 3. Replaces the contents of `*this` with `[p, p + r)` (which sets the length of `*this` to `r`). Invalidates all pointers and references to the range `[p, p + count]`. The program is ill-formed if `r` does not have an [integer-like type](../../iterator/weakly_incrementable#Integer-like_types "cpp/iterator/weakly incrementable"). The behavior is undefined if `std::move(op)(p, count)` throws an exception or modifies `p` or `count`, `r` is not in the range `[0, count]`, or any character in range `[p, p + r)` has an indeterminate value. Implementations are recommended to avoid unnecessary copies and allocations by, e.g., making `p` equal to the pointer to beginning of storage of characters allocated for `*this` after the call, which can be identical to the existing storage of `*this` if `count` is less than or equal to `this->[capacity()](capacity "cpp/string/basic string/capacity")`. ### Parameters | | | | | --- | --- | --- | | count | - | the maximal possible new size of the string | | op | - | the function object used for setting the new contents of the string | ### Return value (none). ### Exceptions `[std::length\_error](../../error/length_error "cpp/error/length error")` if `count > this->[max\_size()](max_size "cpp/string/basic string/max size")`. Any exceptions thrown by corresponding `Allocator`. If an exception is thrown from `std::move(op)(p, count)`, the behavior is undefined. Otherwise, if an exception is thrown, this function has no effect. ### Notes `resize_and_overwrite` invalidates all iterators, pointers, and references into `*this`, regardless whether reallocation occurs. Implementations may assume that the contents of the string are not aliased after the call to `resize_and_overwrite`. | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_string_resize_and_overwrite`](../../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | ### Example Link to test the example: [compiler explorer](https://godbolt.org/z/fbbeYGf5h). ``` #include <algorithm> #include <cassert> #include <cstddef> #include <cstring> #include <iomanip> #include <iostream> #include <string> #include <string_view> static_assert(__cpp_lib_string_resize_and_overwrite); constexpr std::string_view fruits[] {"apple", "banana", "coconut", "date", "elderberry"}; int main() { // A simple case, append only fruits[0]. The string size will be increased. std::string s { "Food: " }; s.resize_and_overwrite(16, [sz = s.size()](char* buf, std::size_t buf_size) { const auto to_copy = std::min(buf_size - sz, fruits[0].size()); std::memcpy(buf + sz, fruits[0].data(), to_copy); return sz + to_copy; }); std::cout << "1. " << std::quoted(s) << '\n'; // The size shrinking case. Note, that the user's lambda is always invoked. s.resize_and_overwrite(10, [](char* buf, int n) { return std::find(buf, buf + n, ':') - buf; }); std::cout << "2. " << std::quoted(s) << '\n'; std::cout << "3. Copy data until the buffer is full. Print data and sizes.\n"; std::string food { "Food:" }; const auto resize_to { 27 }; std::cout << "Initially, food.size: " << food.size() << ", food.capacity: " << food.capacity() << ", resize_to: " << resize_to << ", food: " << std::quoted(food) << '\n'; food.resize_and_overwrite( resize_to, [food_size = food.size()](char* p, std::size_t n) noexcept -> std::size_t { // p[0]..p[n] is the assignable range // p[0]..p[min(n, food_size) - 1] is the readable range // (contents initially equal to the original string) // Debug print: std::cout << "In Operation(); n: " << n << '\n'; // Copy fruits to the buffer p while there is enough space. char* first = p + food_size; for (char* const end = p + n; const std::string_view fruit : fruits) { char* last = first + fruit.size() + 1; if (last > end) break; *first++ = ' '; std::ranges::copy(fruit, first); first = last; } const auto final_size { static_cast<std::size_t>(first - p) }; // Debug print: std::cout << "In Operation(); final_size: " << final_size << '\n'; assert(final_size <= n); return final_size; // Return value is the actual new length // of the string, must be in range 0..n }); std::cout << "Finally, food.size: " << food.size() << ", food.capacity: " << food.capacity() << ", food: " << std::quoted(food) << '\n'; } ``` Possible output: ``` 1. "Food: apple" 2. "Food" 3. Copy data until the buffer is full. Print data and sizes. Initially, food.size: 5, food.capacity: 15, resize_to: 27, food: "Food:" In Operation(); n: 27 In Operation(); final_size: 26 Finally, food.size: 26, food.capacity: 30, food: "Food: apple banana coconut" ``` ### See also | | | | --- | --- | | [resize](resize "cpp/string/basic string/resize") | changes the number of characters stored (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::ends_with std::basic\_string<CharT,Traits,Allocator>::ends\_with ====================================================== | | | | | --- | --- | --- | | ``` constexpr bool ends_with( std::basic_string_view<CharT,Traits> sv ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr bool ends_with( CharT c ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr bool ends_with( const CharT* s ) const; ``` | (3) | (since C++20) | Checks if the string ends with the given suffix. The suffix may be one of the following: 1) a string view `sv` (which may be a result of implicit conversion from another `std::basic_string`). 2) a single character `c`. 3) a null-terminated character string `s`. All three overloads effectively return `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>(data(), size()).ends\_with(x)`, where `x` is the parameter. ### Parameters | | | | | --- | --- | --- | | sv | - | a string view which may be a result of implicit conversion from another `std::basic_string` | | c | - | a single character | | s | - | a null-terminated character string | ### Return value `true` if the string ends with the provided suffix, `false` otherwise. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_starts_ends_with`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string_view> #include <string> template <typename SuffixType> void test_suffix_print(const std::string& str, SuffixType suffix) { std::cout << '\'' << str << "' ends with '" << suffix << "': " << str.ends_with(suffix) << '\n'; } int main() { std::boolalpha(std::cout); auto helloWorld = std::string("hello world"); test_suffix_print(helloWorld, std::string_view("world")); test_suffix_print(helloWorld, std::string_view("goodbye")); test_suffix_print(helloWorld, 'd'); test_suffix_print(helloWorld, 'x'); } ``` Output: ``` 'hello world' ends with 'world': true 'hello world' ends with 'goodbye': false 'hello world' ends with 'd': true 'hello world' ends with 'x': false ``` ### See also | | | | --- | --- | | [starts\_with](starts_with "cpp/string/basic string/starts with") (C++20) | checks if the string starts with the given prefix (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 of `std::basic_string_view<CharT,Traits>`) | | [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 of `std::basic_string_view<CharT,Traits>`) | | [contains](contains "cpp/string/basic string/contains") (C++23) | checks if the string contains the given substring or character (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 of `std::basic_string_view<CharT,Traits>`) | | [compare](compare "cpp/string/basic string/compare") | compares two strings (public member function) | | [substr](substr "cpp/string/basic string/substr") | returns a substring (public member function) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::insert std::basic\_string<CharT,Traits,Allocator>::insert ================================================== | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& insert( size_type index, size_type count, CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& insert( size_type index, size_type count, CharT ch ); ``` | (since C++20) | | | (2) | | | ``` basic_string& insert( size_type index, const CharT* s ); ``` | (until C++20) | | ``` constexpr basic_string& insert( size_type index, const CharT* s ); ``` | (since C++20) | | | (3) | | | ``` basic_string& insert( size_type index, const CharT* s, size_type count ); ``` | (until C++20) | | ``` constexpr basic_string& insert( size_type index, const CharT* s, size_type count ); ``` | (since C++20) | | | (4) | | | ``` basic_string& insert( size_type index, const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& insert( size_type index, const basic_string& str ); ``` | (since C++20) | | | (5) | | | ``` basic_string& insert( size_type index, const basic_string& str, size_type index_str, size_type count ); ``` | (until C++14) | | ``` basic_string& insert( size_type index, const basic_string& str, size_type index_str, size_type count = npos ); ``` | (since C++14) (until C++20) | | ``` constexpr basic_string& insert( size_type index, const basic_string& str, size_type index_str, size_type count = npos ); ``` | (since C++20) | | | (6) | | | ``` iterator insert( iterator pos, CharT ch ); ``` | (until C++11) | | ``` iterator insert( const_iterator pos, CharT ch ); ``` | (since C++11) (until C++20) | | ``` constexpr iterator insert( const_iterator pos, CharT ch ); ``` | (since C++20) | | | (7) | | | ``` void insert( iterator pos, size_type count, CharT ch ); ``` | (until C++11) | | ``` iterator insert( const_iterator pos, size_type count, CharT ch ); ``` | (since C++11) (until C++20) | | ``` constexpr iterator insert( const_iterator pos, size_type count, CharT ch ); ``` | (since C++20) | | | (8) | | | ``` 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) | | | (9) | | | ``` iterator insert( const_iterator pos, std::initializer_list<CharT> ilist ); ``` | (since C++11) (until C++20) | | ``` constexpr iterator insert( const_iterator pos, std::initializer_list<CharT> ilist ); ``` | (since C++20) | | | (10) | | | ``` template< class StringViewLike > basic_string& insert( size_type pos, const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template< class StringViewLike > constexpr basic_string& insert( size_type pos, const StringViewLike& t ); ``` | (since C++20) | | | (11) | | | ``` template< class StringViewLike > basic_string& insert( size_type index, const StringViewLike& t, size_type index_str, size_type count = npos ); ``` | (since C++17) (until C++20) | | ``` template< class StringViewLike > constexpr basic_string& insert( size_type index, const StringViewLike& t, size_type index_str, size_type count = npos ); ``` | (since C++20) | Inserts characters into the string. 1) Inserts `count` copies of character `ch` at the position `index` 2) Inserts null-terminated character string pointed to by `s` at the position `index`. The length of the string is determined by the first null character using `Traits::length(s)`. 3) Inserts the characters in the range `[s, s+count)` at the position `index`. The range can contain null characters. 4) Inserts string `str` at the position `index` 5) Inserts a string, obtained by `str.substr(index_str, count)` at the position `index` 6) Inserts character `ch` before the character pointed by `pos` 7) Inserts `count` copies of character `ch` before the element (if any) pointed by `pos` 8) Inserts characters from the range `[first, last)` before the element (if any) pointed by `pos`. This overload does not participate in overload resolution if `InputIt` does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). (since C++11) 9) Inserts elements from initializer list `ilist` before the element (if any) pointed by `pos` 10) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then inserts the elements from `sv` before the element (if any) pointed by `pos`, as if by `insert(pos, sv.data(), sv.size())`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 11) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then inserts, before the element (if any) pointed by `pos`, the characters from the subview `[index_str, index_str+count)` of `sv`. If the requested subview lasts past the end of `sv`, or if `count == npos`, the resulting subview is `[index_str, sv.size())`. If `index_str > sv.size()`, or if `index > size()`, `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. ### Parameters | | | | | --- | --- | --- | | index | - | position at which the content will be inserted | | pos | - | iterator before which the characters will be inserted | | ch | - | character to insert | | count | - | number of characters to insert | | s | - | pointer to the character string to insert | | str | - | string to insert | | first, last | - | range defining characters to insert | | index\_str | - | position of the first character in the string `str` to insert | | ilist | - | `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` to insert the characters from | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) to insert the characters from | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-5,10-11) `*this` 6-9) An iterator which refers to the copy of the first inserted character or `pos` if no characters were inserted (`count==0` or `first==last` or `ilist.size()==0`) ### Exceptions 1-4, 10) Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `index > size()`. 5) Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `index > size()` or if `index_str > str.size()`. 11) Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `index > size()` or if `index_str > sv.size()`. In all cases, throws `[std::length\_error](../../error/length_error "cpp/error/length error")` if `size() + ins_count > max_size()` where `ins_count` is the number of characters that will be inserted and may throw any exceptions thrown by `Allocator::allocate`. | | | | --- | --- | | In any case, if an exception is thrown for any reason, this function has no effect (strong exception guarantee). | (since C++11) | ### Example ``` #include <cassert> #include <iterator> #include <string> using namespace std::string_literals; int main() { std::string s = "xmplr"; // insert(size_type index, size_type count, char ch) s.insert(0, 1, 'E'); assert("Exmplr" == s); // insert(size_type index, const char* s) s.insert(2, "e"); assert("Exemplr" == s); // insert(size_type index, string const& str) s.insert(6, "a"s); assert("Exemplar" == s); // insert(size_type index, string const& str, // size_type index_str, size_type count) s.insert(8, " is an example string."s, 0, 14); assert("Exemplar is an example" == s); // insert(const_iterator pos, char ch) s.insert(s.cbegin() + s.find_first_of('n') + 1, ':'); assert("Exemplar is an: example" == s); // insert(const_iterator pos, size_type count, char ch) s.insert(s.cbegin() + s.find_first_of(':') + 1, 2, '='); assert("Exemplar is an:== example" == s); // insert(const_iterator pos, InputIt first, InputIt last) { std::string seq = " string"; s.insert(s.begin() + s.find_last_of('e') + 1, std::begin(seq), std::end(seq)); assert("Exemplar is an:== example string" == s); } // insert(const_iterator pos, std::initializer_list<char>) s.insert(s.cbegin() + s.find_first_of('g') + 1, { '.' }); assert("Exemplar is an:== example string." == s); } ``` ### 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 effect of overload (8) referred to a non-existing overload | refers to overload (4) correctly | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | ### See also | | | | --- | --- | | [append](append "cpp/string/basic string/append") | appends characters to the end (public member function) | | [push\_back](push_back "cpp/string/basic string/push back") | appends a character to the end (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::get_allocator std::basic\_string<CharT,Traits,Allocator>::get\_allocator ========================================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const; ``` | | (until C++20) | | ``` constexpr allocator_type get_allocator() const noexcept; ``` | | (since C++20) | Returns the allocator associated with the string. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. ### See also | | | | --- | --- | | [allocator](../../memory/allocator "cpp/memory/allocator") | the default allocator (class template) | | [allocator\_traits](../../memory/allocator_traits "cpp/memory/allocator traits") (C++11) | provides information about allocator types (class template) | | [uses\_allocator](../../memory/uses_allocator "cpp/memory/uses allocator") (C++11) | checks if the specified type supports uses-allocator construction (class template) | cpp std::basic_string<CharT,Traits,Allocator>::basic_string std::basic\_string<CharT,Traits,Allocator>::basic\_string ========================================================= | | | | | --- | --- | --- | | | (1) | | | ``` basic_string(); explicit basic_string( const Allocator& alloc ); ``` | (until C++17) | | ``` basic_string() noexcept(noexcept( Allocator() )) : basic_string( Allocator() ) {} explicit basic_string( const Allocator& alloc ) noexcept; ``` | (since C++17) (until C++20) | | ``` constexpr basic_string() noexcept(noexcept( Allocator() )) : basic_string( Allocator() ) {} explicit constexpr basic_string( const Allocator& alloc ) noexcept; ``` | (since C++20) | | | (2) | | | ``` basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() ); ``` | (until C++20) | | ``` constexpr basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (3) | | | ``` basic_string( const basic_string& other, size_type pos, const Allocator& alloc = Allocator() ); ``` | (until C++20) | | ``` constexpr basic_string( const basic_string& other, size_type pos, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (3) | | | ``` basic_string( const basic_string& other, size_type pos, size_type count, const Allocator& alloc = Allocator() ); ``` | (until C++20) | | ``` constexpr basic_string( const basic_string& other, size_type pos, size_type count, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (4) | | | ``` basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() ); ``` | (until C++20) | | ``` constexpr basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (5) | | | ``` basic_string( const CharT* s, const Allocator& alloc = Allocator() ); ``` | (until C++20) | | ``` constexpr basic_string( const CharT* s, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (6) | | | ``` template< class InputIt > basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); ``` | (until C++20) | | ``` template< class InputIt > constexpr basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (7) | | | ``` basic_string( const basic_string& other ); ``` | (until C++20) | | ``` constexpr basic_string( const basic_string& other ); ``` | (since C++20) | | | (7) | | | ``` basic_string( const basic_string& other, const Allocator& alloc ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string( const basic_string& other, const Allocator& alloc ); ``` | (since C++20) | | | (8) | | | ``` basic_string( basic_string&& other ) noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr basic_string( basic_string&& other ) noexcept; ``` | (since C++20) | | | (8) | | | ``` basic_string( basic_string&& other, const Allocator& alloc ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string( basic_string&& other, const Allocator& alloc ); ``` | (since C++20) | | | (9) | | | ``` basic_string( std::initializer_list<CharT> ilist, const Allocator& alloc = Allocator() ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string( std::initializer_list<CharT> ilist, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (10) | | | ``` template< class StringViewLike > explicit basic_string( const StringViewLike& t, const Allocator& alloc = Allocator() ); ``` | (since C++17) (until C++20) | | ``` template< class StringViewLike > explicit constexpr basic_string( const StringViewLike& t, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | | (11) | | | ``` template< class StringViewLike > basic_string( const StringViewLike& t, size_type pos, size_type n, const Allocator& alloc = Allocator() ); ``` | (since C++17) (until C++20) | | ``` template< class StringViewLike > constexpr basic_string( const StringViewLike& t, size_type pos, size_type n, const Allocator& alloc = Allocator() ); ``` | (since C++20) | | ``` basic_string( std::nullptr_t ) = delete; ``` | (12) | (since C++23) | Constructs new string from a variety of data sources and optionally using user supplied allocator `alloc`. 1) Default constructor. Constructs empty string (zero size and unspecified capacity). If no allocator is supplied, allocator is obtained from a default-constructed instance. 2) Constructs the string with `count` copies of character `ch`. This constructor is not used for [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") if the `Allocator` type that would be deduced does not qualify as an allocator. (since C++17) 3) Constructs the string with a substring `[pos, pos+count)` of `other`. If `count == npos`, if `count` is not specified, or if the requested substring lasts past the end of the string, the resulting substring is `[pos, other.size())`. 4) Constructs the string with the first `count` characters of character string pointed to by `s`. `s` can contain null characters. The length of the string is `count`. The behavior is undefined if `[s, s + count)` is not a valid range. 5) Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by `s`. The length of the string is determined by the first null character. The behavior is undefined if `[s, s + Traits::length(s))` is not a valid range (for example, if `s` is a null pointer). This constructor is not used for [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") if the `Allocator` type that would be deduced does not qualify as an allocator. (since C++17) 6) Constructs the string with the contents of the range `[first, last)`. | | | | --- | --- | | If `InputIt` is an integral type, equivalent to overload (2), as if by `basic_string(static_cast<size_type>(first), static_cast<value_type>(last), alloc)`. | (until C++11) | | This constructor only participates in overload resolution if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | (since C++11) | 7) Copy constructor. Constructs the string with a copy of the contents of `other`. 8) Move constructor. Constructs the string with the contents of `other` using move semantics. `other` is left in valid, but unspecified state. 9) Constructs the string with the contents of the initializer list `ilist`. 10) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then initializes the string with the contents of `sv`, as if by `basic_string(sv.data(), sv.size(), alloc)`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 11) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then initializes the string with the subrange `[pos, pos + n)` of `sv` as if by `basic_string(sv.substr(pos, n), alloc)`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` . 12) `basic_string` cannot be constructed from `nullptr`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this string | | count | - | size of the resulting string | | ch | - | value to initialize the string with | | pos | - | position of the first character to include | | first, last | - | range to copy the characters from | | s | - | pointer to an array of characters to use as source to initialize the string with | | other | - | another string to use as source to initialize the string with | | ilist | - | `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` to initialize the string with | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) to initialize the string with | ### Complexity 1) constant 2-4) linear in `count` 5) linear in length of `s` 6) linear in distance between `first` and `last` 7) linear in size of `other` 8) constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear 9) linear in size of `ilist` ### Exceptions 3) `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > other.size()` 8) Throws nothing if `alloc == str.get_allocator()` 11) `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos` is out of range Throws `[std::length\_error](../../error/length_error "cpp/error/length error")` if the length of the constructed string would exceed `[max\_size()](max_size "cpp/string/basic string/max size")` (for example, if `count > max_size()` for (2)). Calls to `Allocator::allocate` may throw. ### Notes Initialization with a [string literal](../../language/string_literal "cpp/language/string literal") that contains embedded `'\0'` characters uses the overload (5), which stops at the first null character. This can be avoided by specifying a different constructor or by using [`operator""s`](operator%22%22s "cpp/string/basic string/operator\"\"s"): ``` std::string s1 = "ab\0\0cd"; // s1 contains "ab" std::string s2{"ab\0\0cd", 6}; // s2 contains "ab\0\0cd" std::string s3 = "ab\0\0cd"s; // s3 contains "ab\0\0cd" ``` ### Example ``` #include <iostream> #include <iomanip> #include <cassert> #include <iterator> #include <string> #include <cctype> int main() { { std::cout << "1) string(); "; std::string s; assert(s.empty() && (s.length() == 0) && (s.size() == 0)); std::cout << "s.capacity(): " << s.capacity() << '\n'; // unspecified } { std::cout << "2) string(size_type count, charT ch): "; std::string s(4, '='); std::cout << std::quoted(s) << '\n'; // "====" } { std::cout << "3) string(const string& other, size_type pos, size_type count): "; std::string const other("Exemplary"); std::string s(other, 0, other.length()-1); std::cout << quoted(s) << '\n'; // "Exemplar" } { std::cout << "4) string(const string& other, size_type pos): "; std::string const other("Mutatis Mutandis"); std::string s(other, 8); std::cout << quoted(s) << '\n'; // "Mutandis", i.e. [8, 16) } { std::cout << "5) string(charT const* s, size_type count): "; std::string s("C-style string", 7); std::cout << quoted(s) << '\n'; // "C-style", i.e. [0, 7) } { std::cout << "6) string(charT const* s): "; std::string s("C-style\0string"); std::cout << quoted(s) << '\n'; // "C-style" } { std::cout << "7) string(InputIt first, InputIt last): "; char mutable_c_str[] = "another C-style string"; std::string s(std::begin(mutable_c_str)+8, std::end(mutable_c_str)-1); std::cout << quoted(s) << '\n'; // "C-style string" } { std::cout << "8) string(string&): "; std::string const other("Exemplar"); std::string s(other); std::cout << quoted(s) << '\n'; // "Exemplar" } { std::cout << "9) string(string&&): "; std::string s(std::string("C++ by ") + std::string("example")); std::cout << quoted(s) << '\n'; // "C++ by example" } { std::cout << "α) string(std::initializer_list<charT>): "; std::string s({ 'C', '-', 's', 't', 'y', 'l', 'e' }); std::cout << quoted(s) << '\n'; // "C-style" } { // before C++11, overload resolution selects string(InputIt first, InputIt last) // [with InputIt = int] which behaves *as if* string(size_type count, charT ch) // after C++11 the InputIt constructor is disabled for integral types and calls: std::cout << "β) string(size_type count, charT ch) is called: "; std::string s(3, std::toupper('a')); std::cout << quoted(s) << '\n'; // "AAA" } { [[maybe_unused]] auto zero = [] { /* ... */ return nullptr; }; // std::string s{ zero() }; // Before C++23: throws std::logic_error // Since C++23: won't compile, see overload (12) } } ``` Possible output: ``` 1) string(); s.capacity(): 15 2) string(size_type count, charT ch): "====" 3) string(const string& other, size_type pos, size_type count): "Exemplar" 4) string(const string& other, size_type pos): "Mutandis" 5) string(charT const* s, size_type count): "C-style" 6) string(charT const* s): "C-style" 7) string(InputIt first, InputIt last): "C-style string" 8) string(string&): "Exemplar" 9) string(string&&): "C++ by example" α) string(std::initializer_list<charT>): "C-style" β) string(size_type count, charT ch) is called: "AAA" ``` ### 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 2583](https://cplusplus.github.io/LWG/issue2583) | C++98 | there is no way to supply an allocator for`basic_string(str, pos)` | there's a constructor for `basic_string(str, pos, alloc)` | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [LWG 3076](https://cplusplus.github.io/LWG/issue3076) | C++17 | two constructors may cause ambiguities in classtemplate argument deduction | constrained | ### See also | | | | --- | --- | | [assign](assign "cpp/string/basic string/assign") | assign characters to a string (public member function) | | [operator=](operator= "cpp/string/basic string/operator=") | assigns values to the string (public member function) | | [to\_string](to_string "cpp/string/basic string/to string") (C++11) | converts an integral or floating point value to `string` (function) | | [to\_wstring](to_wstring "cpp/string/basic string/to wstring") (C++11) | converts an integral or floating point value to `wstring` (function) | | [(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 of `std::basic_string_view<CharT,Traits>`) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::shrink_to_fit std::basic\_string<CharT,Traits,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/string/basic string/capacity")` to `[size()](size "cpp/string/basic string/size")`. It depends on the implementation if the request is fulfilled. If (and only if) reallocation takes place, all pointers, references, and iterators are invalidated. ### Parameters (none). ### Return value (none). ### Complexity | | | | --- | --- | | (unspecified). | (until C++17) | | Linear in the size of the string. | (since C++17) | ### Example ``` #include <iostream> #include <string> int main() { std::string s; std::cout << "Size of std::string is " << sizeof s << " bytes\n" << "Default-constructed capacity is " << s.capacity() << " and size is " << s.size() << '\n'; for (int i=0; i<42; i++) s.append(" 42 "); std::cout << "Capacity after 42 appends is " << s.capacity() << " and size is " << s.size() << '\n'; s.clear(); std::cout << "Capacity after clear() is " << s.capacity() << " and size is " << s.size() << '\n'; s.shrink_to_fit(); std::cout << "Capacity after shrink_to_fit() is " << s.capacity() << " and size is " << s.size() << '\n'; } ``` Possible output: ``` GCC output: Size of std::string is 32 bytes Default-constructed capacity is 15 and size 0 Capacity after 42 appends is 240 and size 168 Capacity after clear() is 240 and size 0 Capacity after shrink_to_fit() is 15 and size 0 clang output (with -stdlib=libc++): Size of std::string is 24 bytes Default-constructed capacity is 22 and size is 0 Capacity after 42 appends is 191 and size is 168 Capacity after clear() is 191 and size is 0 Capacity after shrink_to_fit() is 22 and size is 0 ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string/size") | returns the number of characters (public member function) | | [capacity](capacity "cpp/string/basic string/capacity") | returns the number of characters that can be held in currently allocated storage (public member function) | | [resize](resize "cpp/string/basic string/resize") | changes the number of characters stored (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::rbegin, std::basic_string<CharT,Traits,Allocator>::crbegin std::basic\_string<CharT,Traits,Allocator>::rbegin, std::basic\_string<CharT,Traits,Allocator>::crbegin ======================================================================================================= | | | | | --- | --- | --- | | | (1) | | | ``` reverse_iterator rbegin(); ``` | (until C++11) | | ``` reverse_iterator rbegin() noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr reverse_iterator rbegin() noexcept; ``` | (since C++20) | | | (2) | | | ``` 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) | | | (3) | | | ``` 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 character of the reversed string. It corresponds to the last character of the non-reversed string. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value reverse iterator to the first character. ### Complexity Constant. ### Example ``` #include <iostream> #include <algorithm> #include <iterator> #include <string> int main() { std::string s("Exemplar!"); *s.rbegin() = 'y'; std::cout << s << '\n'; // "Exemplary" std::string c; std::copy(s.crbegin(), s.crend(), std::back_inserter(c)); std::cout << c << '\n'; // "yralpmexE" } ``` Output: ``` Exemplary yralpmexE ``` ### See also | | | | --- | --- | | [rend crend](rend "cpp/string/basic string/rend") (C++11) | returns a reverse 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::c_str std::basic\_string<CharT,Traits,Allocator>::c\_str ================================================== | | | | | --- | --- | --- | | ``` const CharT* c_str() const; ``` | | (until C++11) | | ``` const CharT* c_str() const noexcept; ``` | | (since C++11) (until C++20) | | ``` constexpr const CharT* c_str() const noexcept; ``` | | (since C++20) | Returns a pointer to a null-terminated character array with data equivalent to those stored in the string. The pointer is such that the range `[c_str(); c_str() + size()]` is valid and the values in it correspond to the values stored in the string with an additional null character after the last position. The pointer obtained from `c_str()` may be invalidated by: * Passing a non-const reference to the string to any standard library function, or * Calling non-const member functions on the string, excluding `[operator[]](operator_at "cpp/string/basic string/operator at")`, `[at()](at "cpp/string/basic string/at")`, `[front()](front "cpp/string/basic string/front")`, `[back()](back "cpp/string/basic string/back")`, `[begin()](begin "cpp/string/basic string/begin")`, `[rbegin()](rbegin "cpp/string/basic string/rbegin")`, `[end()](end "cpp/string/basic string/end")` and `[rend()](rend "cpp/string/basic string/rend")` (since C++11). Writing to the character array accessed through `c_str()` is undefined behavior. | | | | --- | --- | | `c_str()` and `[data()](data "cpp/string/basic string/data")` perform the same function. | (since C++11) | ### Parameters (none). ### Return value Pointer to the underlying character storage. | | | | --- | --- | | `c_str()[i] == operator[](i)` for every `i` in `[0, size())`. | (until C++11) | | `c_str() + i == [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(operator[](i))` for every `i` in `[0, size()]`. | (since C++11) | ### Complexity Constant. ### Notes The pointer obtained from `c_str()` may only be treated as a pointer to a null-terminated character string if the string object does not contain other null characters. ### Example ``` #include <algorithm> #include <cassert> #include <cstring> #include <string> extern "C" { void c_func(const char* c_str) { printf("c_func called with '%s'\n", c_str); } } int main() { std::string const s("Emplary"); const char* p = s.c_str(); assert(s.size() == std::strlen(p)); assert(std::equal(s.begin(), s.end(), p)); assert(std::equal(p, p + s.size(), s.begin())); assert('\0' == *(p + s.size())); c_func(s.c_str()); } ``` Output: ``` c_func called with 'Emplary' ``` ### See also | | | | --- | --- | | [front](front "cpp/string/basic string/front") (C++11) | accesses the first character (public member function) | | [back](back "cpp/string/basic string/back") (C++11) | accesses the last character (public member function) | | [data](data "cpp/string/basic string/data") | returns a pointer to the first character of a string (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::rfind std::basic\_string<CharT,Traits,Allocator>::rfind ================================================= | | | | | --- | --- | --- | | | (1) | | | ``` size_type rfind( const basic_string& str, size_type pos = npos ) const; ``` | (until C++11) | | ``` size_type rfind( const basic_string& str, size_type pos = npos ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type rfind( const basic_string& str, size_type pos = npos ) const noexcept; ``` | (since C++20) | | | (2) | | | ``` size_type rfind( const CharT* s, size_type pos, size_type count ) const; ``` | (until C++20) | | ``` constexpr size_type rfind( const CharT* s, size_type pos, size_type count ) const; ``` | (since C++20) | | | (3) | | | ``` size_type rfind( const CharT* s, size_type pos = npos ) const; ``` | (until C++20) | | ``` constexpr size_type rfind( const CharT* s, size_type pos = npos ) const; ``` | (since C++20) | | | (4) | | | ``` size_type rfind( CharT ch, size_type pos = npos ) const; ``` | (until C++11) | | ``` size_type rfind( CharT ch, size_type pos = npos ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type rfind( CharT ch, size_type pos = npos ) const noexcept; ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > size_type rfind( const StringViewLike& t, size_type pos = npos ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr size_type rfind( const StringViewLike& t, size_type pos = npos ) const noexcept(/* see below */); ``` | (since C++20) | Finds the last substring equal to the given character sequence. Search begins at `pos`, i.e. the found substring must not begin in a position following `pos`. If `[npos](npos "cpp/string/basic string/npos")` or any value not smaller than `[size()](size "cpp/string/basic string/size")`-1 is passed as `pos`, whole string will be searched. 1) Finds the last substring equal to `str`. 2) Finds the last substring equal to the range `[s, s+count)`. This range can include null characters. 3) Finds the last substring equal to the character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 4) Finds the last character equal to `ch`. 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then finds the last substring equal to the contents of `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. In all cases, equality is checked by calling [Traits::eq](../char_traits/cmp "cpp/string/char traits/cmp"). ### Parameters | | | | | --- | --- | --- | | str | - | string to search for | | pos | - | position at which to begin searching | | count | - | length of substring to search for | | s | - | pointer to a character string to search for | | ch | - | character to search for | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) to search for | ### Return value Position of the first character of the found substring or `[npos](npos "cpp/string/basic string/npos")` if no such substring is found. Note that this is an offset from the start of the string, not the end. If searching for an empty string (`str.size()`, `count`, or `Traits::length(s)` is zero) returns `pos` (the empty string is found immediately) unless `pos > size()` (including the case where `pos == npos`), in which case returns `size()`. Otherwise, if `[size()](size "cpp/string/basic string/size")` is zero, `[npos](npos "cpp/string/basic string/npos")` is always returned. ### Exceptions 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>)` ### Example ``` #include <string> #include <iostream> void print(std::string::size_type n, std::string const &s) { if (n == std::string::npos) { std::cout << "not found\n"; } else { std::cout << "found: \"" << s.substr(n) << "\" at " << n << '\n'; } } int main() { std::string::size_type n; std::string const s = "This is a string"; // search backwards from end of string n = s.rfind("is"); print(n, s); // search backwards from position 4 n = s.rfind("is", 4); print(n, s); // find a single character n = s.rfind('s'); print(n, s); // find a single character n = s.rfind('q'); print(n, s); } ``` Output: ``` found: "is a string" at 5 found: "is is a string" at 2 found: "string" at 10 not found ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | overload (3) and (4) were noexcept | removed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++11C++17 | noexcept for overload (4)/(5) was accidently dropped by LWG2064/LWG2946 | restored | ### See also | | | | --- | --- | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function) | | [find\_first\_not\_of](find_first_not_of "cpp/string/basic string/find first not of") | find first absence of characters (public member function) | | [find\_last\_of](find_last_of "cpp/string/basic string/find last of") | find last occurrence of characters (public member function) | | [find\_last\_not\_of](find_last_not_of "cpp/string/basic string/find last not of") | find last absence of characters (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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::at std::basic\_string<CharT,Traits,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 character at specified location `pos`. Bounds checking is performed, exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` will be thrown on invalid access. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the character to return | ### Return value Reference to the requested character. ### Exceptions Throws `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos >= size()`. ### Complexity Constant. ### Example ``` #include <stdexcept> #include <iostream> #include <string> int main() { std::string s("message"); // for capacity s = "abc"; s.at(2) = 'x'; // ok std::cout << s << '\n'; std::cout << "string size = " << s.size() << '\n'; std::cout << "string capacity = " << s.capacity() << '\n'; try { // This will throw since the requested offset is greater than the current size. s.at(3) = 'x'; } catch (std::out_of_range const& exc) { std::cout << exc.what() << '\n'; } } ``` Possible output: ``` abx string size = 3 string capacity = 7 basic_string::at ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/string/basic string/operator at") | 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::operator+= std::basic\_string<CharT,Traits,Allocator>::operator+= ====================================================== | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& operator+=( const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& operator+=( const basic_string& str ); ``` | (since C++20) | | | (2) | | | ``` basic_string& operator+=( CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& operator+=( CharT ch ); ``` | (since C++20) | | | (3) | | | ``` basic_string& operator+=( const CharT* s ); ``` | (until C++20) | | ``` constexpr basic_string& operator+=( const CharT* s ); ``` | (since C++20) | | | (4) | | | ``` basic_string& operator+=( std::initializer_list<CharT> ilist ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string& operator+=( std::initializer_list<CharT> ilist ); ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > basic_string& operator+=( const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& operator+=( const StringViewLike& t ); ``` | (since C++20) | Appends additional characters to the string. 1) Appends string `str` 2) Appends character `ch` 3) Appends the null-terminated character string pointed to by `s`. 4) Appends characters in the initializer list `ilist`. 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then appends characters in the string view `sv` as if by `append(sv)`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. ### Parameters | | | | | --- | --- | --- | | str | - | string to append | | ch | - | character value to append | | s | - | pointer to a null-terminated character string to append | | ilist | - | `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` with the characters to append | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) with the characters to append | ### Return value `*this`. ### Complexity There are no standard complexity guarantees, typical implementations behave similar to [`std::vector::insert`](../../container/vector/insert "cpp/container/vector/insert"). ### Exceptions If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11). If the operation would result in `size() > max_size()`, throws `[std::length\_error](../../error/length_error "cpp/error/length error")`. ### Notes Overload (2) can accept any types that are implicitly convertible to `CharT`. For `std::string`, where `CharT` is `char`, the set of acceptable types includes all arithmetic types. This may have unintended effects. ### 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 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | ### Example ``` #include <iostream> #include <iomanip> #include <string> int main() { std::string str; str.reserve(50); //reserves sufficient storage space to avoid memory reallocation std::cout << std::quoted(str) << '\n'; //empty string str += "This"; std::cout << std::quoted(str) << '\n'; str += std::string(" is "); std::cout << std::quoted(str) << '\n'; str += 'a'; std::cout << std::quoted(str) << '\n'; str += {' ','s','t','r','i','n','g','.'}; std::cout << std::quoted(str) << '\n'; str += 76.85; // equivalent to str += static_cast<char>(76.85), might not be the intent std::cout << std::quoted(str) << '\n'; } ``` Output: ``` "" "This" "This is " "This is a" "This is a string." "This is a string.L" ``` ### See also | | | | --- | --- | | [append](append "cpp/string/basic string/append") | appends characters to the end (public member function) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::operator[] std::basic\_string<CharT,Traits,Allocator>::operator[] ====================================================== | | | | | --- | --- | --- | | | (1) | | | ``` reference operator[]( size_type pos ); ``` | (until C++20) | | ``` constexpr reference operator[]( size_type pos ); ``` | (since C++20) | | | (2) | | | ``` 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 character at specified location `pos`. No bounds checking is performed. If `pos > size()`, the behavior is undefined. | | | | --- | --- | | 1) If `pos == size()`, the behavior is undefined. 2) If `pos == size()`, a reference to the character with value `CharT()` (the null character) is returned. | (until C++11) | | If `pos == size()`, a reference to the character with value `CharT()` (the null character) is returned. For the first (non-const) version, the behavior is undefined if this character is modified to any value other than `CharT()` . | (since C++11) | ### Parameters | | | | | --- | --- | --- | | pos | - | position of the character to return | ### Return value Reference to the requested character. ### Complexity Constant. ### Example ``` #include <iostream> #include <string> int main() { std::string const e("Exemplar"); for (unsigned i = e.length() - 1; i != 0; i /= 2) std::cout << e[i]; std::cout << '\n'; const char* c = &e[0]; std::cout << c << '\n'; // print as a C string //Change the last character of s into a 'y' std::string s("Exemplar "); s[s.size()-1] = 'y'; // equivalent to s.back() = 'y'; std::cout << s << '\n'; } ``` Output: ``` rmx Exemplar Exemplary ``` ### See also | | | | --- | --- | | [at](at "cpp/string/basic string/at") | accesses the specified character with bounds checking (public member function) | | [front](front "cpp/string/basic string/front") (C++11) | accesses the first character (public member function) | | [back](back "cpp/string/basic string/back") (C++11) | accesses the last character (public member function) | | [operator[]](../basic_string_view/operator_at "cpp/string/basic string view/operator at") (C++17) | accesses the specified character (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::swap std::basic\_string<CharT,Traits,Allocator>::swap ================================================ | | | | | --- | --- | --- | | ``` void swap( basic_string& other ); ``` | | (until C++17) | | ``` void swap( basic_string& other ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` constexpr void swap( basic_string& other ) noexcept(/* see below */); ``` | | (since C++20) | Exchanges the contents of the string with those of `other`. All iterators and references may be invalidated. | | | | --- | --- | | The behavior is undefined if `Allocator` does not propagate on swap and the allocators of `*this` and `other` are unequal. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | string to exchange the contents with | ### Return value (none). ### Complexity Constant. | | | | --- | --- | | Exceptions [`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) | ### Example ``` #include <string> #include <iostream> int main() { std::string a = "AAA"; std::string b = "BBB"; std::cout << "before swap" << '\n'; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; a.swap(b); std::cout << "after swap" << '\n'; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; } ``` Output: ``` before swap a: AAA b: BBB after swap a: BBB b: AAA ``` ### 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) | | [swap](../basic_string_view/swap "cpp/string/basic string view/swap") (C++17) | swaps the contents (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::max_size std::basic\_string<CharT,Traits,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 string 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 string. ### Parameters (none). ### Return value Maximum number of characters. ### Complexity Constant. ### Example ``` #include <iostream> #include <string> #include <climits> int main() { std::string s; std::cout << "Maximum size of a string is " << s.max_size() << " (" << std::hex << std::showbase << s.max_size() << "), pointer size: " << std::dec << CHAR_BIT*sizeof(void*) << " bits\n"; } ``` Possible output: ``` Maximum size of a string is 9223372036854775807 (0x7fffffffffffffff), pointer size: 64 bits ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string/size") | 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::to_wstring std::to\_wstring ================ | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` std::wstring to_wstring( int value ); ``` | (1) | (since C++11) | | ``` std::wstring to_wstring( long value ); ``` | (2) | (since C++11) | | ``` std::wstring to_wstring( long long value ); ``` | (3) | (since C++11) | | ``` std::wstring to_wstring( unsigned value ); ``` | (4) | (since C++11) | | ``` std::wstring to_wstring( unsigned long value ); ``` | (5) | (since C++11) | | ``` std::wstring to_wstring( unsigned long long value ); ``` | (6) | (since C++11) | | ``` std::wstring to_wstring( float value ); ``` | (7) | (since C++11) | | ``` std::wstring to_wstring( double value ); ``` | (8) | (since C++11) | | ``` std::wstring to_wstring( long double value ); ``` | (9) | (since C++11) | Converts a numeric value to `[std::wstring](../basic_string "cpp/string/basic string")`. 1) Converts a signed decimal integer to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%d", value)` would produce for sufficiently large `buf`. 2) Converts a signed decimal integer to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%ld", value)` would produce for sufficiently large `buf`. 3) Converts a signed decimal integer to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%lld", value)` would produce for sufficiently large `buf`. 4) Converts an unsigned decimal integer to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%u", value)` would produce for sufficiently large `buf`. 5) Converts an unsigned decimal integer to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%lu", value)` would produce for sufficiently large `buf`. 6) Converts an unsigned decimal integer to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%llu", value)` would produce for sufficiently large `buf`. 7,8) Converts a floating point value to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%f", value)` would produce for sufficiently large `buf`. 9) Converts a floating point value to a wide string with the same content as what `[std::swprintf](http://en.cppreference.com/w/cpp/io/c/fwprintf)(buf, sz, L"%Lf", value)` would produce for sufficiently large `buf`. ### Parameters | | | | | --- | --- | --- | | value | - | a numeric value to convert | ### Return value a wide string holding the converted value. ### Exceptions May throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` from the `[std::wstring](../basic_string "cpp/string/basic string")` constructor. ### Example ``` #include <iostream> #include <string> int main() { for (const double f : { 23.43, 1e-9, 1e40, 1e-40, 123456789. }) { std::wcout << "std::wcout: " << f << '\n' << "to_wstring: " << std::to_wstring(f) << "\n\n"; } } ``` Output: ``` std::wcout: 23.43 to_wstring: 23.430000 std::wcout: 1e-09 to_wstring: 0.000000 std::wcout: 1e+40 to_wstring: 10000000000000000303786028427003666890752.000000 std::wcout: 1e-40 to_wstring: 0.000000 std::wcout: 1.23457e+08 to_wstring: 123456789.000000 ``` ### See also | | | | --- | --- | | [to\_string](to_string "cpp/string/basic string/to string") (C++11) | converts an integral or floating point value to `string` (function) | cpp std::basic_string<CharT,Traits,Allocator>::append std::basic\_string<CharT,Traits,Allocator>::append ================================================== | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& append( size_type count, CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& append( size_type count, CharT ch ); ``` | (since C++20) | | | (2) | | | ``` basic_string& append( const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& append( const basic_string& str ); ``` | (since C++20) | | | (3) | | | ``` basic_string& append( const basic_string& str, size_type pos, size_type count ); ``` | (until C++14) | | ``` basic_string& append( const basic_string& str, size_type pos, size_type count = npos ); ``` | (since C++14) (until C++20) | | ``` constexpr basic_string& append( const basic_string& str, size_type pos, size_type count = npos ); ``` | (since C++20) | | | (4) | | | ``` basic_string& append( const CharT* s, size_type count ); ``` | (until C++20) | | ``` constexpr basic_string& append( const CharT* s, size_type count ); ``` | (since C++20) | | | (5) | | | ``` basic_string& append( const CharT* s ); ``` | (until C++20) | | ``` constexpr basic_string& append( const CharT* s ); ``` | (since C++20) | | | (6) | | | ``` template< class InputIt > basic_string& append( InputIt first, InputIt last ); ``` | (until C++20) | | ``` template< class InputIt > constexpr basic_string& append( InputIt first, InputIt last ); ``` | (since C++20) | | | (7) | | | ``` basic_string& append( std::initializer_list<CharT> ilist ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string& append( std::initializer_list<CharT> ilist ); ``` | (since C++20) | | | (8) | | | ``` template < class StringViewLike > basic_string& append( const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& append( const StringViewLike& t ); ``` | (since C++20) | | | (9) | | | ``` template < class StringViewLike > basic_string& append( const StringViewLike& t, size_type pos, size_type count = npos ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& append( const StringViewLike& t, size_type pos, size_type count = npos ); ``` | (since C++20) | Appends additional characters to the string. 1) Appends `count` copies of character `ch` 2) Appends string `str` 3) Appends a substring `[pos, pos+count)` of `str`. If the requested substring lasts past the end of the string, or if `count == npos`, the appended substring is `[pos, size())`. If `pos > str.size()`, `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. 4) Appends characters in the range `[s, s + count)`. This range can contain null characters. 5) Appends the null-terminated character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 6) Appends characters in the range `[first, last)`. | | | | --- | --- | | This overload has the same effect as overload (1) if `InputIt` is an integral type. | (until C++11) | | This overload only participates in overload resolution if `InputIt` qualifies as an [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | (since C++11) | 7) Appends characters from the initializer list `ilist`. 8) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then appends all characters from `sv` as if by `append(sv.data(), sv.size())`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 9) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then appends the characters from the subview `[pos, pos+count)` of `sv`. If the requested subview extends past the end of `sv`, or if `count == npos`, the appended subview is `[pos, sv.size())`. If `pos >= sv.size()`, `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. ### Parameters | | | | | --- | --- | --- | | count | - | number of characters to append | | pos | - | the index of the first character to append | | ch | - | character value to append | | first, last | - | range of characters to append | | str | - | string to append | | s | - | pointer to the character string to append | | ilist | - | initializer list with the characters to append | | t | - | object convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")` with the characters to append | ### Return value `*this`. ### Complexity There are no standard complexity guarantees, typical implementations behave similar to [std::vector::insert](../../container/vector/insert "cpp/container/vector/insert"). ### Exceptions If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11). If the operation would result in `size() > max_size()`, throws `[std::length\_error](../../error/length_error "cpp/error/length error")`. ### 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 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | ### Example ``` #include <string> #include <iostream> int main() { std::basic_string<char> str = "string"; const char* cptr = "C-string"; const char carr[] = "Two and one"; std::string output; // 1) Append a char 3 times. // Notice, this is the only overload accepting chars. output.append(3, '*'); std::cout << "1) " << output << "\n"; // 2) Append a whole string output.append(str); std::cout << "2) " << output << "\n"; // 3) Append part of a string (last 3 letters, in this case) output.append(str, 3, 3); std::cout << "3) " << output << "\n"; // 4) Append part of a C-string // Notice, because `append` returns *this, we can chain calls together output.append(1, ' ').append(carr, 4); std::cout << "4) " << output << "\n"; // 5) Append a whole C-string output.append(cptr); std::cout << "5) " << output << "\n"; // 6) Append range output.append(&carr[3], std::end(carr)); std::cout << "6) " << output << "\n"; // 7) Append initializer list output.append({ ' ', 'l', 'i', 's', 't' }); std::cout << "7) " << output << "\n"; } ``` Output: ``` 1) *** 2) ***string 3) ***stringing 4) ***stringing Two 5) ***stringing Two C-string 6) ***stringing Two C-string and one 7) ***stringing Two C-string and one list ``` ### See also | | | | --- | --- | | [operator+=](operator_plus_= "cpp/string/basic string/operator+=") | appends characters to the end (public member 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) | | [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) | cpp std::basic_string<CharT,Traits,Allocator>::find_last_of std::basic\_string<CharT,Traits,Allocator>::find\_last\_of ========================================================== | | | | | --- | --- | --- | | | (1) | | | ``` size_type find_last_of( const basic_string& str, size_type pos = npos ) const; ``` | (until C++11) | | ``` constexpr size_type find_last_of( const basic_string& str, size_type pos = npos ) const noexcept; ``` | (since C++11) (until C++20) | | | (2) | | | ``` size_type find_last_of( const CharT* s, size_type pos, size_type count ) const; ``` | (until C++11) | | ``` constexpr size_type find_last_of( const CharT* s, size_type pos, size_type count ) const; ``` | (since C++11) | | | (3) | | | ``` size_type find_last_of( const CharT* s, size_type pos = npos ) const; ``` | (until C++20) | | ``` constexpr size_type find_last_of( const CharT* s, size_type pos = npos ) const; ``` | (since C++20) | | | (4) | | | ``` size_type find_last_of( CharT ch, size_type pos = npos ) const; ``` | (until C++11) | | ``` size_type find_last_of( CharT ch, size_type pos = npos ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_last_of( CharT ch, size_type pos = npos ) const noexcept; ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > size_type find_last_of( const StringViewLike& t, size_type pos = npos ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr size_type find_last_of( const StringViewLike& t, size_type pos = npos ) const noexcept(/* see below */); ``` | (since C++20) | Finds the last character equal to one of characters in the given character sequence. The exact search algorithm is not specified. The search considers only the interval [0, pos]. If the character is not present in the interval, `[npos](npos "cpp/string/basic string/npos")` will be returned. 1) Finds the last character equal to one of characters in `str`. 2) Finds the last character equal to one of characters in range `[s, s+count)`. This range can include null characters. 3) Finds the last character equal to one of characters in character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 4) Finds the last character equal to `ch`. 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then finds the last character equal to one of characters in `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. In all cases, equality is checked by calling [Traits::eq](../char_traits/cmp "cpp/string/char traits/cmp"). ### Parameters | | | | | --- | --- | --- | | str | - | string identifying characters to search for | | pos | - | position at which the search is to finish | | count | - | length of character string identifying characters to search for | | s | - | pointer to a character string identifying characters to search for | | ch | - | character to search for | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) identifying characters to search for | ### Return value Position of the found character or `[npos](npos "cpp/string/basic string/npos")` if no such character is found. ### Exceptions 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>)` ### Example ``` #include<string> #include<iostream> int main() { const std::string path="/root/config"; auto const pos=path.find_last_of('/'); const auto leaf=path.substr(pos+1); std::cout << leaf << '\n'; } ``` Output: ``` config ``` ### 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 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | overload (3) and (4) were noexcept | removed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++11C++17 | noexcept for overload (4)/(5) was accidently dropped by LWG2064/LWG2946 | restored | ### See also | | | | --- | --- | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [rfind](rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function) | | [find\_first\_not\_of](find_first_not_of "cpp/string/basic string/find first not of") | find first absence of characters (public member function) | | [find\_last\_not\_of](find_last_not_of "cpp/string/basic string/find last not of") | find last absence 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 of `std::basic_string_view<CharT,Traits>`) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::replace std::basic\_string<CharT,Traits,Allocator>::replace =================================================== | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& replace( size_type pos, size_type count, const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& replace( size_type pos, size_type count, const basic_string& str ); ``` | (since C++20) | | | (1) | | | ``` basic_string& replace( const_iterator first, const_iterator last, const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& replace( const_iterator first, const_iterator last, const basic_string& str ); ``` | (since C++20) | | | (2) | | | ``` basic_string& replace( size_type pos, size_type count, const basic_string& str, size_type pos2, size_type count2 ); ``` | (until C++14) | | ``` basic_string& replace( size_type pos, size_type count, const basic_string& str, size_type pos2, size_type count2 = npos ); ``` | (since C++14) (until C++20) | | ``` constexpr basic_string& replace( size_type pos, size_type count, const basic_string& str, size_type pos2, size_type count2 = npos ); ``` | (since C++20) | | | (3) | | | ``` template< class InputIt > basic_string& replace( const_iterator first, const_iterator last, InputIt first2, InputIt last2 ); ``` | (until C++20) | | ``` template< class InputIt > constexpr basic_string& replace( const_iterator first, const_iterator last, InputIt first2, InputIt last2 ); ``` | (since C++20) | | | (4) | | | ``` basic_string& replace( size_type pos, size_type count, const CharT* cstr, size_type count2 ); ``` | (until C++20) | | ``` constexpr basic_string& replace( size_type pos, size_type count, const CharT* cstr, size_type count2 ); ``` | (since C++20) | | | (4) | | | ``` basic_string& replace( const_iterator first, const_iterator last, const CharT* cstr, size_type count2 ); ``` | (until C++20) | | ``` constexpr basic_string& replace( const_iterator first, const_iterator last, const CharT* cstr, size_type count2 ); ``` | (since C++20) | | | (5) | | | ``` basic_string& replace( size_type pos, size_type count, const CharT* cstr ); ``` | (until C++20) | | ``` constexpr basic_string& replace( size_type pos, size_type count, const CharT* cstr ); ``` | (since C++20) | | | (5) | | | ``` basic_string& replace( const_iterator first, const_iterator last, const CharT* cstr ); ``` | (until C++20) | | ``` constexpr basic_string& replace( const_iterator first, const_iterator last, const CharT* cstr ); ``` | (since C++20) | | | (6) | | | ``` basic_string& replace( size_type pos, size_type count, size_type count2, CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& replace( size_type pos, size_type count, size_type count2, CharT ch ); ``` | (since C++20) | | | (6) | | | ``` basic_string& replace( const_iterator first, const_iterator last, size_type count2, CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& replace( const_iterator first, const_iterator last, size_type count2, CharT ch ); ``` | (since C++20) | | | (7) | | | ``` basic_string& replace( const_iterator first, const_iterator last, std::initializer_list<CharT> ilist ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string& replace( const_iterator first, const_iterator last, std::initializer_list<CharT> ilist ); ``` | (since C++20) | | | (8) | | | ``` template < class StringViewLike > basic_string& replace( size_type pos, size_type count, const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& replace( size_type pos, size_type count, const StringViewLike& t ); ``` | (since C++20) | | | (8) | | | ``` template < class StringViewLike > basic_string& replace( const_iterator first, const_iterator last, const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& replace( const_iterator first, const_iterator last, const StringViewLike& t ); ``` | (since C++20) | | | (9) | | | ``` template < class StringViewLike > basic_string& replace( size_type pos, size_type count, const StringViewLike& t, size_type pos2, size_type count2 = npos ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& replace( size_type pos, size_type count, const StringViewLike& t, size_type pos2, size_type count2 = npos ); ``` | (since C++20) | Replaces the part of the string indicated by either `[pos, pos + count)` or `[first, last)` with a new string. The new string can be one of: 1) string `str`; 2) substring `[pos2, pos2 + count2)` of `str`, except if `count2==npos` or if would extend past `str.size()`, `[pos2, str.size())` is used. 3) characters in the range `[first2, last2)`. | | | | --- | --- | | This overload has the same effect as overload (6) if `InputIt` is an integral type. | (until C++11) | | This overload only participates in overload resolution if `InputIt` qualifies as an [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | (since C++11) | 4) characters in the range `[cstr, cstr + count2)`; 5) characters in the range `[cstr, cstr + Traits::length(cstr))`; 6) `count2` copies of character `ch`; 7) characters in the initializer list `ilist`; 8) characters of a string view `sv`, converted from `t` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`. These overloads participate in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false` 9) subview `[pos2, pos2 + count2)` of a string view `sv`, converted from `t` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, except if `count2==npos` or if it would extend past `sv.size()`, `[pos2, sv.size())` is used. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. ### Parameters | | | | | --- | --- | --- | | pos | - | start of the substring that is going to be replaced | | count | - | length of the substring that is going to be replaced | | first, last | - | range of characters that is going to be replaced | | str | - | string to use for replacement | | pos2 | - | start of the substring to replace with | | count2 | - | number of characters to replace with | | cstr | - | pointer to the character string to use for replacement | | ch | - | character value to use for replacement | | first2, last2 | - | range of characters to use for replacement | | ilist | - | initializer list with the characters to use for replacement | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) with the characters to use for replacement | ### Return value `*this`. ### Exceptions * `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > length()` or `pos2 > str.length()` * `[std::length\_error](../../error/length_error "cpp/error/length error")` if the resulting string will exceed maximum possible string length (`[max\_size()](max_size "cpp/string/basic string/max size")`) In any case, if an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11). ### Example ``` #include <cassert> #include <cstddef> #include <iostream> #include <string> #include <string_view> std::size_t replace_all(std::string& inout, std::string_view what, std::string_view with); std::size_t remove_all(std::string& inout, std::string_view what); void test_replace_remove_all(); int main() { std::string str{"The quick brown fox jumps over the lazy dog."}; str.replace(10, 5, "red"); // (5) str.replace(str.begin(), str.begin() + 3, 1, 'A'); // (6) std::cout << str << "\n\n"; test_replace_remove_all(); } std::size_t replace_all(std::string& inout, std::string_view what, std::string_view with) { std::size_t count{}; for (std::string::size_type pos{}; inout.npos != (pos = inout.find(what.data(), pos, what.length())); pos += with.length(), ++count) { inout.replace(pos, what.length(), with.data(), with.length()); } return count; } std::size_t remove_all(std::string& inout, std::string_view what) { return replace_all(inout, what, ""); } void test_replace_remove_all() { std::string str2{"ftp: ftpftp: ftp:"}; std::cout << "#1 " << str2 << '\n'; auto count = replace_all(str2, "ftp", "http"); assert(count == 4); std::cout << "#2 " << str2 << '\n'; count = replace_all(str2, "ftp", "http"); assert(count == 0); std::cout << "#3 " << str2 << '\n'; count = remove_all(str2, "http"); assert(count == 4); std::cout << "#4 " << str2 << '\n'; } ``` Output: ``` A quick red fox jumps over the lazy dog. #1 ftp: ftpftp: ftp: #2 http: httphttp: http: #3 http: httphttp: http: #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 1323](https://cplusplus.github.io/LWG/issue1323) | C++98 | several overloads of `replace` use `iterator` and not `const_iterator` | use `const_iterator` | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | ### See also | | | | --- | --- | | [regex\_replace](../../regex/regex_replace "cpp/regex/regex replace") (C++11) | replaces occurrences of a regular expression with formatted replacement text (function template) | | [replacereplace\_if](../../algorithm/replace "cpp/algorithm/replace") | replaces all values satisfying specific criteria with another value (function template) | cpp std::basic_string<CharT,Traits,Allocator>::back std::basic\_string<CharT,Traits,Allocator>::back ================================================ | | | | | --- | --- | --- | | ``` CharT& back(); ``` | | (since C++11) (until C++20) | | ``` constexpr CharT& back(); ``` | | (since C++20) | | ``` const CharT& back() const; ``` | | (since C++11) (until C++20) | | ``` constexpr const CharT& back() const; ``` | | (since C++20) | Returns reference to the last character in the string. The behavior is undefined if `empty() == true`. ### Parameters (none). ### Return value reference to the last character, equivalent to `operator[](size() - 1)`. ### Complexity Constant. ### Example ``` #include <iostream> #include <string> int main() { { std::string s("Exemplary"); char& back = s.back(); back = 's'; std::cout << s << '\n'; // "Exemplars" } { std::string const c("Exemplary"); char const& back = c.back(); std::cout << back << '\n'; // 'y' } } ``` Output: ``` Exemplars y ``` ### See also | | | | --- | --- | | [front](front "cpp/string/basic string/front") (C++11) | 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::assign std::basic\_string<CharT,Traits,Allocator>::assign ================================================== | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& assign( size_type count, CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& assign( size_type count, CharT ch ); ``` | (since C++20) | | | (2) | | | ``` basic_string& assign( const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& assign( const basic_string& str ); ``` | (since C++20) | | | (3) | | | ``` basic_string& assign( const basic_string& str, size_type pos, size_type count ); ``` | (until C++14) | | ``` basic_string& assign( const basic_string& str, size_type pos, size_type count = npos); ``` | (since C++14) (until C++20) | | ``` constexpr basic_string& assign( const basic_string& str, size_type pos, size_type count = npos); ``` | (since C++20) | | | (4) | | | ``` basic_string& assign( basic_string&& str ); ``` | (since C++11) (until C++17) | | ``` basic_string& assign( basic_string&& str ) noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` constexpr basic_string& assign( basic_string&& str ) noexcept(/* see below */); ``` | (since C++20) | | | (5) | | | ``` basic_string& assign( const CharT* s, size_type count ); ``` | (until C++20) | | ``` constexpr basic_string& assign( const CharT* s, size_type count ); ``` | (since C++20) | | | (6) | | | ``` basic_string& assign( const CharT* s ); ``` | (until C++20) | | ``` constexpr basic_string& assign( const CharT* s ); ``` | (since C++20) | | | (7) | | | ``` template< class InputIt > basic_string& assign( InputIt first, InputIt last ); ``` | (until C++20) | | ``` template< class InputIt > constexpr basic_string& assign( InputIt first, InputIt last ); ``` | (since C++20) | | | (8) | | | ``` basic_string& assign( std::initializer_list<CharT> ilist ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string& assign( std::initializer_list<CharT> ilist ); ``` | (since C++20) | | | (9) | | | ``` template < class StringViewLike > basic_string& assign( const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& assign( const StringViewLike& t ); ``` | (since C++20) | | | (10) | | | ``` template < class StringViewLike > basic_string& assign( const StringViewLike& t, size_type pos, size_type count = npos); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr basic_string& assign( const StringViewLike& t, size_type pos, size_type count = npos); ``` | (since C++20) | Replaces the contents of the string. 1) Replaces the contents with `count` copies of character `ch`. 2) Replaces the contents with a copy of `str`. Equivalent to `*this = str;`. In particular, allocator propagation may take place. (since C++11) 3) Replaces the contents with a substring `[pos, pos+count)` of `str`. If the requested substring lasts past the end of the string, or if `count == npos`, the resulting substring is `[pos, str.size())`. If `pos > str.size()`, `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. 4) Replaces the contents with those of `str` using move semantics. Equivalent to `*this = std::move(str)`. In particular, allocator propagation may take place. 5) Replaces the contents with copies of the characters in the range `[s, s+count)`. This range can contain null characters. 6) Replaces the contents with those of null-terminated character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 7) Replaces the contents with copies of the characters in the range `[first, last)`. This overload does not participate in overload resolution if `InputIt` does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). (since C++11) 8) Replaces the contents with those of the initializer list `ilist`. 9) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then replaces the contents with those of `sv`, as if by `assign(sv.data(), sv.size())`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 10) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then replaces the contents with the characters from the subview `[pos, pos+count)` of `sv`. If the requested subview lasts past the end of `sv`, or if `count == npos`, the resulting subview is `[pos, sv.size())`. If `pos > sv.size()`, `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. ### Parameters | | | | | --- | --- | --- | | count | - | size of the resulting string | | pos | - | index of the first character to take | | ch | - | value to initialize characters of the string with | | first, last | - | range to copy the characters from | | str | - | string to be used as source to initialize the characters with | | s | - | pointer to a character string to use as source to initialize the string with | | ilist | - | `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` to initialize the characters of the string with | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) to initialize the characters of the string with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value `*this`. ### Complexity 1) linear in `count` 2) linear in size of `str` 3) linear in `count` 4) constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 5) linear in `count` 6) linear in size of `s` 7) linear in distance between `first` and `last` 8) linear in size of `ilist` ### Exceptions If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11). If the operation would result in `size() > max_size()`, throws `[std::length\_error](../../error/length_error "cpp/error/length error")`. | | | | --- | --- | | 4) [`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) | ### Example ``` #include <iostream> #include <iterator> #include <string> int main() { std::string s; // assign(size_type count, CharT ch) s.assign(4, '='); std::cout << s << '\n'; // "====" std::string const c("Exemplary"); // assign(basic_string const& str) s.assign(c); std::cout << c << " == " << s <<'\n'; // "Exemplary == Exemplary" // assign(basic_string const& str, size_type pos, size_type count) s.assign(c, 0, c.length()-1); std::cout << s << '\n'; // "Exemplar"; // assign(basic_string&& str) s.assign(std::string("C++ by ") + "example"); std::cout << s << '\n'; // "C++ by example" // assign(charT const* s, size_type count) s.assign("C-style string", 7); std::cout << s << '\n'; // "C-style" // assign(charT const* s) s.assign("C-style\0string"); std::cout << s << '\n'; // "C-style" char mutable_c_str[] = "C-style string"; // assign(InputIt first, InputIt last) s.assign(std::begin(mutable_c_str), std::end(mutable_c_str)-1); std::cout << s << '\n'; // "C-style string" // assign(std::initializer_list<charT> ilist) s.assign({ 'C', '-', 's', 't', 'y', 'l', 'e' }); std::cout << s << '\n'; // "C-style" } ``` Output: ``` ==== Exemplary == Exemplary Exemplar C++ by example C-style C-style C-style string C-style ``` ### 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 2063](https://cplusplus.github.io/LWG/issue2063) | C++11 | non-normative note stated that swap is a valid implementation of move-assign | corrected to require move assignment | | [LWG 2579](https://cplusplus.github.io/LWG/issue2579) | C++11 | `assign(const basic_string&)` doesn't propagate allocators | made to propagate allocators if needed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | ### See also | | | | --- | --- | | [(constructor)](basic_string "cpp/string/basic string/basic string") | constructs a `basic_string` (public member function) | | [operator=](operator= "cpp/string/basic string/operator=") | assigns values to the string (public member function) |
programming_docs
cpp std::to_string std::to\_string =============== | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` std::string to_string( int value ); ``` | (1) | (since C++11) | | ``` std::string to_string( long value ); ``` | (2) | (since C++11) | | ``` std::string to_string( long long value ); ``` | (3) | (since C++11) | | ``` std::string to_string( unsigned value ); ``` | (4) | (since C++11) | | ``` std::string to_string( unsigned long value ); ``` | (5) | (since C++11) | | ``` std::string to_string( unsigned long long value ); ``` | (6) | (since C++11) | | ``` std::string to_string( float value ); ``` | (7) | (since C++11) | | ``` std::string to_string( double value ); ``` | (8) | (since C++11) | | ``` std::string to_string( long double value ); ``` | (9) | (since C++11) | Converts a numeric value to `[std::string](../basic_string "cpp/string/basic string")`. 1) Converts a signed integer to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%d", value)` would produce for sufficiently large `buf`. 2) Converts a signed integer to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%ld", value)` would produce for sufficiently large `buf`. 3) Converts a signed integer to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%lld", value)` would produce for sufficiently large `buf`. 4) Converts an unsigned integer to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%u", value)` would produce for sufficiently large `buf`. 5) Converts an unsigned integer to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%lu", value)` would produce for sufficiently large `buf`. 6) Converts an unsigned integer to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%llu", value)` would produce for sufficiently large `buf`. 7,8) Converts a floating point value to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%f", value)` would produce for sufficiently large `buf`. 9) Converts a floating point value to a string with the same content as what `[std::sprintf](http://en.cppreference.com/w/cpp/io/c/fprintf)(buf, "%Lf", value)` would produce for sufficiently large `buf`. ### Parameters | | | | | --- | --- | --- | | value | - | a numeric value to convert | ### Return value a string holding the converted value. ### Exceptions May throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` from the `[std::string](../basic_string "cpp/string/basic string")` constructor. ### Notes * With floating point types `std::to_string` may yield unexpected results as the number of significant digits in the returned string can be zero, see the example. * The return value may differ significantly from what `std::cout` prints by default, see the example. * `std::to_string` relies on the current locale for formatting purposes, and therefore concurrent calls to `std::to_string` from multiple threads may result in partial serialization of calls. C++17 provides [`std::to_chars`](../../utility/to_chars "cpp/utility/to chars") as a higher-performance locale-independent alternative. ### Example ``` #include <iostream> #include <string> int main() { for (const double f : {23.43, 1e-9, 1e40, 1e-40, 123456789.}) std::cout << "std::cout: " << f << '\n' << "to_string: " << std::to_string(f) << "\n\n"; } ``` Output: ``` std::cout: 23.43 to_string: 23.430000 std::cout: 1e-09 to_string: 0.000000 std::cout: 1e+40 to_string: 10000000000000000303786028427003666890752.000000 std::cout: 1e-40 to_string: 0.000000 std::cout: 1.23457e+08 to_string: 123456789.000000 ``` ### See also | | | | --- | --- | | [to\_wstring](to_wstring "cpp/string/basic string/to wstring") (C++11) | converts an integral or floating point value to `wstring` (function) | | [stoulstoull](stoul "cpp/string/basic string/stoul") (C++11)(C++11) | converts a string to an unsigned integer (function) | | [stoistolstoll](stol "cpp/string/basic string/stol") (C++11)(C++11)(C++11) | converts a string to a signed integer (function) | | [stofstodstold](stof "cpp/string/basic string/stof") (C++11)(C++11)(C++11) | converts a string to a floating point value (function) | | [to\_chars](../../utility/to_chars "cpp/utility/to chars") (C++17) | converts an integer or floating-point value to a character sequence (function) | cpp std::operator+(std::basic_string) std::operator+(std::basic\_string) ================================== | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (1) | (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (2) | (constexpr since C++20) | | ``` template<class CharT, class Traits, class Alloc> std::basic_string<CharT,Traits,Alloc> operator+( const std::basic_string<CharT,Traits,Alloc>& lhs, CharT rhs ); ``` | (3) | (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (4) | (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( CharT lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (5) | (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( std::basic_string<CharT,Traits,Alloc>&& lhs, std::basic_string<CharT,Traits,Alloc>&& rhs ); ``` | (6) | (since C++11) (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( std::basic_string<CharT,Traits,Alloc>&& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (7) | (since C++11) (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( std::basic_string<CharT,Traits,Alloc>&& lhs, const CharT* rhs ); ``` | (8) | (since C++11) (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( std::basic_string<CharT,Traits,Alloc>&& lhs, CharT rhs ); ``` | (9) | (since C++11) (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( const std::basic_string<CharT,Traits,Alloc>& lhs, std::basic_string<CharT,Traits,Alloc>&& rhs ); ``` | (10) | (since C++11) (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( const CharT* lhs, std::basic_string<CharT,Traits,Alloc>&& rhs ); ``` | (11) | (since C++11) (constexpr since C++20) | | ``` template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( CharT lhs, std::basic_string<CharT,Traits,Alloc>&& rhs ); ``` | (12) | (since C++11) (constexpr since C++20) | Returns a string containing characters from `lhs` followed by the characters from `rhs`. | | | | --- | --- | | The allocator used for the result is: 1-3) `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Alloc>::select\_on\_container\_copy\_construction(lhs.get\_allocator())` 4-5) `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Alloc>::select\_on\_container\_copy\_construction(rhs.get\_allocator())` 6-9) `lhs.get_allocator()` 10-12) `rhs.get_allocator()` In other words, if one operand is a `basic_string` rvalue, its allocator is used; otherwise, `select_on_container_copy_construction` is used on the allocator of the lvalue `basic_string` operand. In each case, the left operand is preferred when both are `basic_string`s of the same value category. For (6-12), all rvalue `basic_string` operands are left in valid but unspecified states. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | lhs | - | string, character, or pointer to the first character in a null-terminated array | | rhs | - | string, character, or pointer to the first character in a null-terminated array | ### Return value A string containing characters from `lhs` followed by the characters from `rhs`, using the allocator determined as above (since C++11). | | | | --- | --- | | Notes `operator+` should be used with great caution when stateful allocators are involved (such as when `[std::pmr::string](../basic_string "cpp/string/basic string")` is used) (since C++17). Prior to [P1165R1](https://wg21.link/P1165R1), the allocator used for the result was determined by historical accident and can vary from overload to overload for no apparent reason. Moreover, for (1-5), the allocator propagation behavior varies across major standard library implementations and differs from the behavior depicted in the standard. Because the allocator used by the result of `operator+` is sensitive to value category, `operator+` is not associative with respect to allocator propagation: ``` using my_string = std::basic_string<char, std::char_traits<char>, my_allocator<char>>; my_string cat(); const my_string& dog(); my_string meow = /* ... */, woof = /* ... */; meow + cat() + /*...*/; // uses select_on_container_copy_construction on meow's allocator woof + dog() + /*...*/; // uses allocator of dog()'s return value instead meow + woof + meow; // uses select_on_container_copy_construction on meow's allocator meow + (woof + meow); // uses SOCCC on woof's allocator instead ``` For a chain of `operator+` invocations, the allocator used for the ultimate result may be controlled by prepending an rvalue `basic_string` with the desired allocator: ``` // use my_favorite_allocator for the final result my_string(my_favorite_allocator) + meow + woof + cat() + dog(); ``` For better and portable control over allocators, member functions like [`append()`](append "cpp/string/basic string/append"), [`insert()`](insert "cpp/string/basic string/insert"), and [`operator+=()`](operator_plus_= "cpp/string/basic string/operator+=") should be used on a result string constructed with the desired allocator. | (since C++11) | ### Example ``` #include <iostream> #include <string> int main() { std::string s1 = "Hello"; std::string s2 = "world"; std::cout << s1 + ' ' + s2 + "!\n"; } ``` Output: ``` Hello world! ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P1165R1](https://wg21.link/P1165R1) | C++11 | allocator propagation is haphazard and inconsistent | made more consistent | ### See also | | | | --- | --- | | [operator+=](operator_plus_= "cpp/string/basic string/operator+=") | appends characters to the end (public member function) | | [append](append "cpp/string/basic string/append") | appends characters to the end (public member function) | | [insert](insert "cpp/string/basic string/insert") | inserts characters (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::data std::basic\_string<CharT,Traits,Allocator>::data ================================================ | | | | | --- | --- | --- | | | (1) | | | ``` const CharT* data() const; ``` | (until C++11) | | ``` const CharT* data() const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr const CharT* data() const noexcept; ``` | (since C++20) | | | (2) | | | ``` CharT* data() noexcept; ``` | (since C++17) (until C++20) | | ``` constexpr CharT* data() noexcept; ``` | (since C++20) | Returns a pointer to the underlying array serving as character storage. The pointer is such that the range. `[``data(); data() + size()``)` (until C++11) `[``data(); data() + size()``]` (since C++11) is valid and the values in it correspond to the values stored in the string. | | | | --- | --- | | The returned array is not required to be null-terminated. If `[empty()](empty "cpp/string/basic string/empty")` returns `true`, the pointer is a non-null pointer that should not be dereferenced. | (until C++11) | | The returned array is null-terminated, that is, `data()` and `[c\_str()](c_str "cpp/string/basic string/c str")` perform the same function. If `[empty()](empty "cpp/string/basic string/empty")` returns `true`, the pointer points to a single null character. | (since C++11) | The pointer obtained from `data()` may be invalidated by: * Passing a non-const reference to the string to any standard library function, or * Calling non-const member functions on the string, excluding [`operator[]()`](operator_at "cpp/string/basic string/operator at"), `[at()](at "cpp/string/basic string/at")`, `[front()](front "cpp/string/basic string/front")`, `[back()](back "cpp/string/basic string/back")`, `[begin()](begin "cpp/string/basic string/begin")`, `[end()](end "cpp/string/basic string/end")`, `[rbegin()](rbegin "cpp/string/basic string/rbegin")`, `[rend()](rend "cpp/string/basic string/rend")`. 1) Modifying the character array accessed through the const overload of `data` has undefined behavior. 2) Modifying the past-the-end null terminator stored at `data()+size()` to any value other than `CharT()` has undefined behavior. ### Parameters (none). ### Return value A pointer to the underlying character storage. | | | | --- | --- | | `data()[i] == operator[](i)` for every `i` in `[0, size())`. | (until C++11) | | `data() + i == [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(operator[](i))` for every `i` in `[0, size()]`. | (since C++11) | ### Complexity Constant. ### Example ``` #include <algorithm> #include <cassert> #include <cstring> #include <string> int main() { std::string const s("Emplary"); assert(s.size() == std::strlen(s.data())); assert(std::equal(s.begin(), s.end(), s.data())); assert(std::equal(s.data(), s.data() + s.size(), s.begin())); assert(0 == *(s.data() + s.size())); } ``` ### See also | | | | --- | --- | | [front](front "cpp/string/basic string/front") (C++11) | accesses the first character (public member function) | | [back](back "cpp/string/basic string/back") (C++11) | accesses the last character (public member function) | | [c\_str](c_str "cpp/string/basic string/c str") | returns a non-modifiable standard C character array version of the string (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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::operator basic_string_view std::basic\_string<CharT,Traits,Allocator>::operator basic\_string\_view ======================================================================== | | | | | --- | --- | --- | | ``` operator std::basic_string_view<CharT, Traits>() const noexcept; ``` | | (since C++17) (until C++20) | | ``` constexpr operator std::basic_string_view<CharT, Traits>() const noexcept; ``` | | (since C++20) | Returns a `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`, constructed as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>(data(), size())`. ### Parameters (none). ### Return value A string view representing the entire contents of the string. ### Notes It is the programmer's responsibility to ensure that the resulting string view does not outlive the string. ``` std::string get_string(); int f(std::string_view sv); int x = f(get_string()); // OK std::string_view sv = get_string(); // Bad: holds a dangling pointer ``` ### Example ``` #include <iostream> #include <string> #include <string_view> void show_wstring_size(std::wstring_view wcstr_v) { std::cout << wcstr_v.size() << " code points\n"; } int main() { std::string cppstr = "ラーメン"; // narrow string std::wstring wcstr = L"ラーメン"; // wide string // Implicit conversion from string to string_view // via std::string::operator string_view: std::string_view cppstr_v = cppstr; std::cout << cppstr_v << '\n' << cppstr_v.size() << " code units\n"; // Implicit conversion from wstring to wstring_view // via std::wstring::operator wstring_view: show_wstring_size(wcstr); } ``` Output: ``` ラーメン 12 code units 4 code points ``` ### See also | | | | --- | --- | | [(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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::find std::basic\_string<CharT,Traits,Allocator>::find ================================================ | | | | | --- | --- | --- | | | (1) | | | ``` size_type find( const basic_string& str, size_type pos = 0 ) const; ``` | (until C++11) | | ``` size_type find( const basic_string& str, size_type pos = 0 ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find( const basic_string& str, size_type pos = 0 ) const noexcept; ``` | (since C++20) | | | (2) | | | ``` size_type find( const CharT* s, size_type pos, size_type count ) const; ``` | (until C++20) | | ``` constexpr size_type find( const CharT* s, size_type pos, size_type count ) const; ``` | (since C++20) | | | (3) | | | ``` size_type find( const CharT* s, size_type pos = 0 ) const; ``` | (until C++20) | | ``` constexpr size_type find( const CharT* s, size_type pos = 0 ) const; ``` | (since C++20) | | | (4) | | | ``` size_type find( CharT ch, size_type pos = 0 ) const; ``` | (until C++11) | | ``` size_type find( CharT ch, size_type pos = 0 ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find( CharT ch, size_type pos = 0 ) const noexcept; ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > size_type find( const StringViewLike& t, size_type pos = 0 ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr size_type find( const StringViewLike& t, size_type pos = 0 ) const noexcept(/* see below */); ``` | (since C++20) | Finds the first substring equal to the given character sequence. Search begins at `pos`, i.e. the found substring must not begin in a position preceding `pos`. 1) Finds the first substring equal to `str`. 2) Finds the first substring equal to the range `[s, s+count)`. This range may contain null characters. 3) Finds the first substring equal to the character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 4) Finds the first character `ch` (treated as a single-character substring by the formal rules below). 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then finds the first substring equal to `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. Formally, a substring `str` is said to be *found* at position `xpos` if all of the following is true: * `xpos >= pos` * `xpos + str.size() <= size()` * for all positions `n` in `str`, `Traits::eq(at(xpos+n), str.at(n))` In particular, this implies that. * a substring can be found only if `pos <= size() - str.size()` * an empty substring is found at `pos` if and only if `pos <= size()` * for a non-empty substring, if `pos >= size()`, the function always returns `[npos](npos "cpp/string/basic string/npos")`. ### Parameters | | | | | --- | --- | --- | | str | - | string to search for | | pos | - | position at which to start the search | | count | - | length of substring to search for | | s | - | pointer to a character string to search for | | ch | - | character to search for | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) to search for | ### Return value Position of the first character of the found substring or `[npos](npos "cpp/string/basic string/npos")` if no such substring is found. ### Exceptions 1-4) Throws nothing. 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>)` ### Example ``` #include <string> #include <iostream> void print(std::string::size_type n, std::string const &s) { if (n == std::string::npos) { std::cout << "not found\n"; } else { std::cout << "found: " << s.substr(n) << '\n'; } } int main() { std::string::size_type n; std::string const s = "This is a string"; // search from beginning of string n = s.find("is"); print(n, s); // search from position 5 n = s.find("is", 5); print(n, s); // find a single character n = s.find('a'); print(n, s); // find a single character n = s.find('q'); print(n, s); } ``` Output: ``` found: is is a string found: is a string found: a string not found ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | overload (3) and (4) were noexcept | removed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++11C++17 | noexcept for overload (4)/(5) was accidently dropped by LWG2064/LWG2946 | restored | ### See also | | | | --- | --- | | [strstr](../byte/strstr "cpp/string/byte/strstr") | finds the first occurrence of a substring of characters (function) | | [wcsstr](../wide/wcsstr "cpp/string/wide/wcsstr") | finds the first occurrence of a wide string within another wide string (function) | | [strchr](../byte/strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) | | [wcschr](../wide/wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) | | [rfind](rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function) | | [find\_first\_not\_of](find_first_not_of "cpp/string/basic string/find first not of") | find first absence of characters (public member function) | | [find\_last\_of](find_last_of "cpp/string/basic string/find last of") | find last occurrence of characters (public member function) | | [find\_last\_not\_of](find_last_not_of "cpp/string/basic string/find last not of") | find last absence of characters (public member function) | | [find](../basic_string_view/find "cpp/string/basic string view/find") (C++17) | find characters in the view (public member function of `std::basic_string_view<CharT,Traits>`) | | [search](../../algorithm/search "cpp/algorithm/search") | searches for a range of elements (function template) |
programming_docs
cpp std::literals::string_literals::operator""s std::literals::string\_literals::operator""s ============================================ | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | | (1) | | | ``` std::string operator""s(const char *str, std::size_t len); ``` | (since C++14) (until C++20) | | ``` constexpr std::string operator""s(const char *str, std::size_t len); ``` | (since C++20) | | ``` constexpr std::u8string operator""s(const char8_t *str, std::size_t len); ``` | (2) | (since C++20) | | | (3) | | | ``` std::u16string operator""s(const char16_t *str, std::size_t len); ``` | (since C++14) (until C++20) | | ``` constexpr std::u16string operator""s(const char16_t *str, std::size_t len); ``` | (since C++20) | | | (4) | | | ``` std::u32string operator""s(const char32_t *str, std::size_t len); ``` | (since C++14) (until C++20) | | ``` constexpr std::u32string operator""s(const char32_t *str, std::size_t len); ``` | (since C++20) | | | (5) | | | ``` std::wstring operator""s(const wchar_t *str, std::size_t len); ``` | (since C++14) (until C++20) | | ``` constexpr std::wstring operator""s(const wchar_t *str, std::size_t len); ``` | (since C++20) | Forms a string literal of the desired type. 1) returns `[std::string](http://en.cppreference.com/w/cpp/string/basic_string){str, len}` 2) returns `[std::u8string](http://en.cppreference.com/w/cpp/string/basic_string){str, len}` 3) returns `[std::u16string](http://en.cppreference.com/w/cpp/string/basic_string){str, len}` 4) returns `[std::u32string](http://en.cppreference.com/w/cpp/string/basic_string){str, len}` 5) returns `[std::wstring](http://en.cppreference.com/w/cpp/string/basic_string){str, len}` ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the beginning of the raw character array literal | | len | - | length of the raw character array literal | ### Return value The string literal. ### Notes These operators are declared in the namespace `std::literals::string_literals`, where both `literals` and `string_literals` are inline namespaces. Access to these operators can be gained with either * `using namespace std::literals`, or * `using namespace std::string_literals`, or * `using namespace std::literals::string_literals`. `[std::chrono::duration](../../chrono/duration "cpp/chrono/duration")` also defines `operator""s`, to represent literal seconds, but it is an arithmetic literal: `10.0s` and `10s` are ten seconds, but `"10"s` is a string. | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_string_udls`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <string> #include <iostream> void print_with_zeros(auto const note, std::string const& s) { std::cout << note; for (const char c : s) { (c ? std::cout << c : std::cout << "₀"); } std::cout << " (size = " << s.size() << ")\n"; } int main() { using namespace std::string_literals; std::string s1 = "abc\0\0def"; std::string s2 = "abc\0\0def"s; print_with_zeros("s1: ", s1); print_with_zeros("s2: ", s2); std::cout << "abcdef"s.substr(1,4) << '\n'; } ``` Output: ``` s1: abc (size = 3) s2: abc₀₀def (size = 8) bcde ``` ### See also | | | | --- | --- | | [(constructor)](basic_string "cpp/string/basic string/basic string") | constructs a `basic_string` (public member function) | | [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) | cpp std::basic_string<CharT,Traits,Allocator>::resize std::basic\_string<CharT,Traits,Allocator>::resize ================================================== | | | | | --- | --- | --- | | | (1) | | | ``` void resize( size_type count ); ``` | (until C++20) | | ``` constexpr void resize( size_type count ); ``` | (since C++20) | | | (2) | | | ``` void resize( size_type count, CharT ch ); ``` | (until C++20) | | ``` constexpr void resize( size_type count, CharT ch ); ``` | (since C++20) | Resizes the string to contain `count` characters. If the current size is less than `count`, additional characters are appended: 1) Initializes appended characters to `CharT()` (`'\0'` if `CharT` is `char`). 2) Initializes appended characters to `ch`. If the current size is greater than `count`, the string is reduced to its first `count` elements. ### Parameters | | | | | --- | --- | --- | | count | - | new size of the string | | ch | - | character to initialize the new characters with | ### Return value (none). ### Exceptions `[std::length\_error](../../error/length_error "cpp/error/length error")` if `count > max_size()`. Any exceptions thrown by corresponding `Allocator`. If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11). ### Example ``` #include <iostream> #include <iomanip> #include <stdexcept> int main() { const unsigned desired_length{ 8 }; std::string long_string( "Where is the end?" ); std::string short_string( "H" ); std::cout << "Basic functionality:\n" << "Shorten:\n" << "1. Before: " << quoted( long_string ) << '\n'; long_string.resize( desired_length ); std::cout << "2. After: " << quoted( long_string ) << '\n'; std::cout << "Lengthen with a given value 'a':\n" << "3. Before: " << quoted( short_string ) << '\n'; short_string.resize( desired_length, 'a' ); std::cout << "4. After: " << quoted( short_string ) << '\n'; std::cout << "Lengthen with char() == " << static_cast<int>(char()) << '\n' << "5. Before: " << quoted( short_string ) << '\n'; short_string.resize( desired_length + 3 ); std::cout << "6. After: \""; for (char c : short_string) { std::cout << (c == char() ? '@' : c); } std::cout << "\"\n\n"; std::cout << "Errors:\n"; { std::string s; try { // size is OK, no length_error // (may throw bad_alloc) s.resize(s.max_size() - 1, 'x'); } catch (const std::bad_alloc& ex) { std::cout << "1. Exception: " << ex.what() << '\n'; } try { // size is OK, no length_error // (may throw bad_alloc) s.resize(s.max_size(), 'x'); } catch (const std::bad_alloc& ex) { std::cout << "2. Exception: " << ex.what() << '\n'; } try { // size is BAD, throw length_error s.resize(s.max_size() + 1, 'x'); } catch (const std::length_error& ex) { std::cout << "3. Length error: " << ex.what() << '\n'; } } } ``` Possible output: ``` Basic functionality: Shorten: 1. Before: "Where is the end?" 2. After: "Where is" Lengthen with a given value 'a': 3. Before: "H" 4. After: "Haaaaaaa" Lengthen with char() == 0 5. Before: "Haaaaaaa" 6. After: "Haaaaaaa@@@" Errors: 1. Exception: std::bad_alloc 2. Exception: std::bad_alloc 3. Length error: basic_string::_M_replace_aux ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string/size") | returns the number of characters (public member function) | | [reserve](reserve "cpp/string/basic string/reserve") | reserves storage (public member function) | | [shrink\_to\_fit](shrink_to_fit "cpp/string/basic string/shrink to fit") (C++11) | reduces memory usage by freeing unused memory (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::find_last_not_of std::basic\_string<CharT,Traits,Allocator>::find\_last\_not\_of =============================================================== | | | | | --- | --- | --- | | | (1) | | | ``` size_type find_last_not_of( const basic_string& str, size_type pos = npos ) const; ``` | (until C++11) | | ``` size_type find_last_not_of( const basic_string& str, size_type pos = npos ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_last_not_of( const basic_string& str, size_type pos = npos ) const noexcept; ``` | (since C++20) | | | (2) | | | ``` size_type find_last_not_of( const CharT* s, size_type pos, size_type count ) const; ``` | (until C++20) | | ``` constexpr size_type find_last_not_of( const CharT* s, size_type pos, size_type count ) const; ``` | (since C++20) | | | (3) | | | ``` size_type find_last_not_of( const CharT* s, size_type pos = npos ) const; ``` | (until C++20) | | ``` constexpr size_type find_last_not_of( const CharT* s, size_type pos = npos ) const; ``` | (since C++20) | | | (4) | | | ``` size_type find_last_not_of( CharT ch, size_type pos = npos ) const; ``` | (until C++11) | | ``` size_type find_last_not_of( CharT ch, size_type pos = npos ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_last_not_of( CharT ch, size_type pos = npos ) const noexcept; ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > size_type find_last_not_of( const StringViewLike& t, size_type pos = npos ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr size_type find_last_not_of( const StringViewLike& t, size_type pos = npos ) const noexcept(/* see below */); ``` | (since C++20) | Finds the last character equal to none of the characters in the given character sequence. The search considers only the interval [0, pos]. If the character is not present in the interval, `[npos](npos "cpp/string/basic string/npos")` will be returned. 1) Finds the last character equal to none of characters in `str`. 2) Finds the last character equal to none of characters in the range `[s, s+count)`. This range can include null characters. 3) Finds the last character equal to none of characters in character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 4) Finds the last character not equal to `ch`. 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then finds the last character equal to none of characters in `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. In all cases, equality is checked by calling [`Traits::eq`](../char_traits/cmp "cpp/string/char traits/cmp"). ### Parameters | | | | | --- | --- | --- | | str | - | string identifying characters to search for | | pos | - | position at which to begin searching | | count | - | length of character string identifying characters to search for | | s | - | pointer to a character string identifying characters to search for | | ch | - | character identifying characters to search for | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) identifying characters to search for | ### Return value Position of the found character or `[npos](npos "cpp/string/basic string/npos")` if no such character is found. ### Exceptions 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<charT, traits>>)` ### Example ``` #include <iostream> #include <string> void show_pos(const std::string& str, std::string::size_type found) { if (found != std::string::npos) { std::cout << "[" << found << "] = \'" << str[found] << "\'\n"; } else { std::cout << "not found" "\n"; } } int main() { std::string str { "abc_123" }; char const* skip_set { "0123456789" }; std::string::size_type str_last_pos { std::string::npos }; show_pos(str, str.find_last_not_of(skip_set)); // [3] = '_' str_last_pos = 2; show_pos(str, str.find_last_not_of(skip_set, str_last_pos)); // [2] = 'c' str_last_pos = 2; show_pos(str, str.find_last_not_of('c', str_last_pos)); // [1] = 'b' const char arr[] { '3','4','5' }; show_pos(str, str.find_last_not_of(arr)); // [5] = '2' str_last_pos = 2; std::string::size_type skip_set_size { 4 }; show_pos(str, str.find_last_not_of(skip_set, str_last_pos, skip_set_size)); // [2] = 'c' show_pos(str, str.find_last_not_of("abc")); // [6] = '3' str_last_pos = 2; show_pos(str, str.find_last_not_of("abc", str_last_pos)); // not found } ``` Output: ``` [3] = '_' [2] = 'c' [1] = 'b' [5] = '2' [2] = 'c' [6] = '3' not found ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | overload (3) and (4) were noexcept | removed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++11C++17 | noexcept for overload (4)/(5) was accidently dropped by LWG2064/LWG2946 | restored | ### See also | | | | --- | --- | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [rfind](rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function) | | [find\_first\_not\_of](find_first_not_of "cpp/string/basic string/find first not of") | find first absence of characters (public member function) | | [find\_last\_of](find_last_of "cpp/string/basic string/find last of") | find last occurrence 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::starts_with std::basic\_string<CharT,Traits,Allocator>::starts\_with ======================================================== | | | | | --- | --- | --- | | ``` constexpr bool starts_with( std::basic_string_view<CharT,Traits> sv ) const noexcept; ``` | (1) | (since C++20) | | ``` constexpr bool starts_with( CharT c ) const noexcept; ``` | (2) | (since C++20) | | ``` constexpr bool starts_with( const CharT* s ) const; ``` | (3) | (since C++20) | Checks if the string begins with the given prefix. The prefix may be one of the following: 1) a string view `sv` (which may be a result of implicit conversion from another `std::basic_string`). 2) a single character `c`. 3) a null-terminated character string `s`. All three overloads effectively return `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>(data(), size()).starts\_with(x)`, where `x` is the parameter. ### Parameters | | | | | --- | --- | --- | | sv | - | a string view which may be a result of implicit conversion from another `std::basic_string` | | c | - | a single character | | s | - | a null-terminated character string | ### Return value `true` if the string begins with the provided prefix, `false` otherwise. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_starts_ends_with`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <string_view> #include <string> template <typename PrefixType> void test_prefix_print(const std::string& str, PrefixType prefix) { std::cout << '\'' << str << "' starts with '" << prefix << "': " << str.starts_with(prefix) << '\n'; } int main() { std::boolalpha(std::cout); auto helloWorld = std::string("hello world"); test_prefix_print(helloWorld, std::string_view("hello")); test_prefix_print(helloWorld, std::string_view("goodbye")); test_prefix_print(helloWorld, 'h'); test_prefix_print(helloWorld, 'x'); } ``` Output: ``` 'hello world' starts with 'hello': true 'hello world' starts with 'goodbye': false 'hello world' starts with 'h': true 'hello world' starts with 'x': false ``` ### See also | | | | --- | --- | | [ends\_with](ends_with "cpp/string/basic string/ends with") (C++20) | checks if the string ends with the given suffix (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 of `std::basic_string_view<CharT,Traits>`) | | [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 of `std::basic_string_view<CharT,Traits>`) | | [contains](contains "cpp/string/basic string/contains") (C++23) | checks if the string contains the given substring or character (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 of `std::basic_string_view<CharT,Traits>`) | | [compare](compare "cpp/string/basic string/compare") | compares two strings (public member function) | | [substr](substr "cpp/string/basic string/substr") | returns a substring (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::erase std::basic\_string<CharT,Traits,Allocator>::erase ================================================= | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& erase( size_type index = 0, size_type count = npos ); ``` | (until C++20) | | ``` constexpr basic_string& erase( size_type index = 0, size_type count = npos ); ``` | (since C++20) | | | (2) | | | ``` iterator erase( iterator position ); ``` | (until C++11) | | ``` iterator erase( const_iterator position ); ``` | (since C++11) (until C++20) | | ``` constexpr iterator erase( const_iterator position ); ``` | (since C++20) | | | (3) | | | ``` 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) | Removes specified characters from the string. 1) Removes `[std::min](http://en.cppreference.com/w/cpp/algorithm/min)(count, size() - index)` characters starting at `index`. 2) Removes the character at `position`. 3) Removes the characters in the range `[first, last)`. ### Parameters | | | | | --- | --- | --- | | index | - | first character to remove | | count | - | number of characters to remove | | position | - | iterator to the character to remove | | first, last | - | range of the characters to remove | ### Return value 1) `*this` 2) iterator pointing to the character immediately following the character erased, or `[end()](end "cpp/string/basic string/end")` if no such character exists 3) iterator pointing to the character `last` pointed to before the erase, or `[end()](end "cpp/string/basic string/end")` if no such character exists ### Exceptions 1) `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `index > size()`. 2-3) Throws nothing. | | | | --- | --- | | In any case, if an exception is thrown for any reason, this function has no effect (strong exception guarantee). | (since C++11) | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <string> int main() { std::string s = "This Is An Example"; std::cout << "1) " << s << '\n'; s.erase(7, 3); // erases " An" using overload (1) std::cout << "2) " << s << '\n'; s.erase(std::find(s.begin(), s.end(), ' ')); // erases first ' '; overload (2) std::cout << "3) " << s << '\n'; s.erase(s.find(' ')); // trims from ' ' to the end of the string; overload (1) std::cout << "4) " << s << '\n'; auto it = std::next(s.begin(), s.find('s')); // obtains iterator to the first 's' s.erase(it, std::next(it, 2)); // erases "sI"; overload (3) std::cout << "5) " << s << '\n'; } ``` Output: ``` 1) This Is An Example 2) This Is Example 3) ThisIs Example 4) ThisIs 5) This ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 27](https://cplusplus.github.io/LWG/issue27) | C++98 | overload (3) did not erase the character `last` pointed to, but it returnedthe iterator pointing to the character immediately following that character | returns an iteratorpointing to that character | ### See also | | | | --- | --- | | [clear](clear "cpp/string/basic string/clear") | clears the contents (public member function) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::capacity std::basic\_string<CharT,Traits,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 characters that the string has currently allocated space for. ### Parameters (none). ### Return value Capacity of the currently allocated storage, i.e. the storage available for storing elements. ### Complexity Constant. ### Notes Memory locations obtained from the allocator but not available for storing any element are not counted in the allocated storage. Note that the null terminator is not an element of the `[std::basic\_string](../basic_string "cpp/string/basic string")`. ### Example ``` #include <iostream> #include <iomanip> #include <string> void show_capacity(std::string const& s) { std::cout << std::quoted(s) << " has capacity " << s.capacity() << ".\n"; } int main() { std::string s{"Exemplar"}; show_capacity(s); s += " is an example string."; show_capacity(s); s.clear(); show_capacity(s); std::cout << "\nDemonstrate the capacity's growth policy." "\nSize: Capacity: Ratio:\n" << std::left; std::string g; auto old_cap {g.capacity()}; for(int mark{}; mark != 5; ++mark) { while (old_cap == g.capacity()) g.push_back('.'); std::cout << std::setw( 7) << g.size() << std::setw(11) << g.capacity() << std::setw(10) << g.capacity() / static_cast<float>(old_cap) << '\n'; old_cap = g.capacity(); } } ``` Possible output: ``` "Exemplar" has capacity 15. "Exemplar is an example string." has capacity 30. "" has capacity 30. Demonstrate the capacity's growth policy. Size: Capacity: Ratio: 16 30 2 31 60 2 61 120 2 121 240 2 241 480 2 ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string/size") | returns the number of characters (public member function) | | [reserve](reserve "cpp/string/basic string/reserve") | reserves storage (public member function) | cpp std::swap(std::basic_string) std::swap(std::basic\_string) ============================= | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_string<CharT, Traits, Alloc> &lhs, std::basic_string<CharT, Traits, Alloc> &rhs ); ``` | | (until C++17) | | ``` template< class CharT, class Traits, class Alloc > void swap( std::basic_string<CharT, Traits, Alloc> &lhs, std::basic_string<CharT, Traits, Alloc> &rhs ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` template< class CharT, class Traits, class Alloc > constexpr void swap( std::basic_string<CharT, Traits, Alloc> &lhs, std::basic_string<CharT, Traits, Alloc> &rhs ) noexcept(/* see below */); ``` | | (since C++20) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_string](../basic_string "cpp/string/basic string")`. Swaps the contents of `lhs` and `rhs`. Equivalent to `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | strings 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) | ### Example ``` #include <string> #include <iostream> int main() { std::string a = "AAAA"; std::string b = "BBB"; std::cout << "before swap" << '\n'; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; std::swap(a,b); std::cout << "after swap" << '\n'; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; } ``` Output: ``` before swap a: AAAA b: BBB after swap a: BBB b: AAAA ``` ### 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 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | non-member `swap` was noexcept and inconsistent with member `swap` | noexcept removed | ### See also | | | | --- | --- | | [swap](swap "cpp/string/basic string/swap") | swaps the contents (public member function) | cpp std::stoi, std::stol, std::stoll std::stoi, std::stol, std::stoll ================================ | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 ); int stoi( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 ); ``` | (1) | (since C++11) | | ``` long stol( const std::string& str, std::size_t* pos = nullptr, int base = 10 ); long stol( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 ); ``` | (2) | (since C++11) | | ``` long long stoll( const std::string& str, std::size_t* pos = nullptr, int base = 10 ); long long stoll( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 ); ``` | (3) | (since C++11) | Interprets a signed integer value in the string `str`. 1) calls `[std::strtol](http://en.cppreference.com/w/cpp/string/byte/strtol)(str.c\_str(), &ptr, base)` or `[std::wcstol](http://en.cppreference.com/w/cpp/string/wide/wcstol)(str.c\_str(), &ptr, base)` 2) calls `[std::strtol](http://en.cppreference.com/w/cpp/string/byte/strtol)(str.c\_str(), &ptr, base)` or `[std::wcstol](http://en.cppreference.com/w/cpp/string/wide/wcstol)(str.c\_str(), &ptr, base)` 3) calls `[std::strtoll](http://en.cppreference.com/w/cpp/string/byte/strtol)(str.c\_str(), &ptr, base)` or `[std::wcstoll](http://en.cppreference.com/w/cpp/string/wide/wcstol)(str.c\_str(), &ptr, base)` Discards any whitespace characters (as identified by calling [`std::isspace`](../byte/isspace "cpp/string/byte/isspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) integer number representation and converts them to an integer value. The valid 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. If `pos` is not a null pointer, then a pointer `ptr` - internal to the conversion functions - will receive the address of the first unconverted character in `str.c_str()`, and the index of that character will be calculated and stored in `*pos`, giving the number of characters that were processed by the conversion. ### Parameters | | | | | --- | --- | --- | | str | - | the string to convert | | pos | - | address of an integer to store the number of characters processed | | base | - | the number base | ### Return value Integer value corresponding to the content of str. ### Exceptions * `[std::invalid\_argument](../../error/invalid_argument "cpp/error/invalid argument")` if no conversion could be performed * `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if the converted value would fall out of the range of the result type or if the underlying function (`std::strtol` or `std::strtoll`) sets `errno` to `[ERANGE](http://en.cppreference.com/w/cpp/error/errno_macros)`. ### Example ``` #include <string> #include <iomanip> #include <utility> #include <iostream> #include <stdexcept> int main() { const auto data = { "45", "+45", " -45", "3.14159", "31337 with words", "words and 2", "12345678901", }; for (const std::string s : data) { std::size_t pos{}; try { std::cout << "std::stoi('" << s << "'): "; const int i {std::stoi(s, &pos)}; std::cout << i << "; pos: " << pos << '\n'; } catch(std::invalid_argument const& ex) { std::cout << "std::invalid_argument::what(): " << ex.what() << '\n'; } catch(std::out_of_range const& ex) { std::cout << "std::out_of_range::what(): " << ex.what() << '\n'; const long long ll {std::stoll(s, &pos)}; std::cout << "std::stoll('" << s << "'): " << ll << "; pos: " << pos << '\n'; } } std::cout << "\nCalling with different radixes:\n"; for (const auto& [s, base]: { std::pair<const char*, int> {"11", 2}, {"22", 3}, {"33", 4}, {"77", 8}, {"99", 10}, {"FF", 16}, {"jJ", 20}, {"Zz", 36}, }) { const int i {std::stoi(s, nullptr, base)}; std::cout << "std::stoi('" << s << "', " << base << "): " << i << '\n'; } } ``` Possible output: ``` std::stoi('45'): 45; pos: 2 std::stoi('+45'): 45; pos: 3 std::stoi(' -45'): -45; pos: 4 std::stoi('3.14159'): 3; pos: 1 std::stoi('31337 with words'): 31337; pos: 5 std::stoi('words and 2'): std::invalid_argument::what(): stoi std::stoi('12345678901'): std::out_of_range::what(): stoi std::stoll('12345678901'): 12345678901; pos: 11 Calling with different radixes: std::stoi('11', 2): 3 std::stoi('22', 3): 8 std::stoi('33', 4): 15 std::stoi('77', 8): 63 std::stoi('99', 10): 99 std::stoi('FF', 16): 255 std::stoi('jJ', 20): 399 std::stoi('Zz', 36): 1295 ``` ### See also | | | | --- | --- | | [stoulstoull](stoul "cpp/string/basic string/stoul") (C++11)(C++11) | converts a string to an unsigned integer (function) | | [stofstodstold](stof "cpp/string/basic string/stof") (C++11)(C++11)(C++11) | converts a string to a floating point 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) | | [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) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [atoiatolatoll](../byte/atoi "cpp/string/byte/atoi") (C++11) | converts a byte string to an integer value (function) | | [to\_string](to_string "cpp/string/basic string/to string") (C++11) | converts an integral or floating point value to `string` (function) | | [to\_wstring](to_wstring "cpp/string/basic string/to wstring") (C++11) | converts an integral or floating point value to `wstring` (function) | cpp std::basic_string<CharT,Traits,Allocator>::npos std::basic\_string<CharT,Traits,Allocator>::npos ================================================ | | | | | --- | --- | --- | | ``` static const size_type npos = -1; ``` | | | This is a special value equal to the maximum value representable by the type `size_type`. The exact meaning depends on context, but it is generally used either as end of string indicator by the functions that expect a string index or as the error indicator by the functions that return a string index. ### Note Although the definition uses `-1`, [`size_type`](../basic_string "cpp/string/basic string") is an unsigned integer type, and the value of `npos` is the largest positive value it can hold, due to [signed-to-unsigned implicit conversion](../../language/implicit_conversion#Integral_conversions "cpp/language/implicit conversion"). This is a portable way to specify the largest value of any unsigned type. ### Example ``` #include <iostream> #include <bitset> #include <string> int main() { // string search functions return npos if nothing is found std::string s = "test"; if(s.find('a') == std::string::npos) std::cout << "no 'a' in 'test'\n"; // functions that take string subsets as arguments // use npos as the "all the way to the end" indicator std::string s2(s, 2, std::string::npos); std::cout << s2 << '\n'; std::bitset<5> b("aaabb", std::string::npos, 'a', 'b'); std::cout << b << '\n'; } ``` Output: ``` no 'a' in 'test' st 00011 ``` ### See also | | | | --- | --- | | [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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::front std::basic\_string<CharT,Traits,Allocator>::front ================================================= | | | | | --- | --- | --- | | ``` CharT& front(); ``` | | (since C++11) (until C++20) | | ``` constexpr CharT& front(); ``` | | (since C++20) | | ``` const CharT& front() const; ``` | | (since C++11) (until C++20) | | ``` constexpr const CharT& front() const; ``` | | (since C++20) | Returns reference to the first character in the string. The behavior is undefined if `empty() == true`. ### Parameters (none). ### Return value reference to the first character, equivalent to `operator[](0)`. ### Complexity Constant. ### Example ``` #include <iostream> #include <string> int main() { { std::string s("Exemplary"); char& f = s.front(); f = 'e'; std::cout << s << '\n'; // "exemplary" } { std::string const c("Exemplary"); char const& f = c.front(); std::cout << &f << '\n'; // "Exemplary" } } ``` Output: ``` exemplary Exemplary ``` ### See also | | | | --- | --- | | [back](back "cpp/string/basic string/back") (C++11) | accesses the last character (public member function) | | [front](../basic_string_view/front "cpp/string/basic string view/front") (C++17) | accesses the first character (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::operator= std::basic\_string<CharT,Traits,Allocator>::operator= ===================================================== | | | | | --- | --- | --- | | | (1) | | | ``` basic_string& operator=( const basic_string& str ); ``` | (until C++20) | | ``` constexpr basic_string& operator=( const basic_string& str ); ``` | (since C++20) | | | (2) | | | ``` basic_string& operator=( basic_string&& str ); ``` | (since C++11) (until C++17) | | ``` basic_string& operator=( basic_string&& str ) noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` constexpr basic_string& operator=( basic_string&& str ) noexcept(/* see below */); ``` | (since C++20) | | | (3) | | | ``` basic_string& operator=( const CharT* s ); ``` | (until C++20) | | ``` constexpr basic_string& operator=( const CharT* s ); ``` | (since C++20) | | | (4) | | | ``` basic_string& operator=( CharT ch ); ``` | (until C++20) | | ``` constexpr basic_string& operator=( CharT ch ); ``` | (since C++20) | | | (5) | | | ``` basic_string& operator=( std::initializer_list<CharT> ilist ); ``` | (since C++11) (until C++20) | | ``` constexpr basic_string& operator=( std::initializer_list<CharT> ilist ); ``` | (since C++20) | | | (6) | | | ``` template<class StringViewLike> basic_string& operator=( const StringViewLike& t ); ``` | (since C++17) (until C++20) | | ``` template<class StringViewLike> constexpr basic_string& operator=( const StringViewLike& t ); ``` | (since C++20) | | ``` constexpr basic_string& operator=( std::nullptr_t ) = delete; ``` | (7) | (since C++23) | Replaces the contents of the string. 1) Replaces the contents with a copy of `str`. If `*this` and `str` are the same object, this function has no effect. 2) Replaces the contents with those of `str` using move semantics. `str` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `str`. If it is `false` and the allocators of `*this` and `str` do not compare equal, `*this` cannot take ownership of the memory owned by `str` and must assign each character individually, allocating additional memory using its own allocator as needed. Unlike other container move assignments, references, pointers, and iterators to `str` may be invalidated. 3) Replaces the contents with those of null-terminated character string pointed to by `s` as if by `assign(s, Traits::length(s))`. 4) Replaces the contents with character `ch` as if by `assign([std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(ch), 1)` 5) Replaces the contents with those of the initializer list `ilist` as if by `assign(ilist.begin(), ilist.size())` 6) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then replaces the contents with those of the `sv` as if by `assign(sv)`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. 7) `basic_string` cannot be assigned from `nullptr`. ### Parameters | | | | | --- | --- | --- | | ch | - | value to initialize characters of the string with | | str | - | string to be used as source to initialize the string with | | s | - | pointer to a null-terminated character string to use as source to initialize the string with | | ilist | - | `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` to initialize the string with | | t | - | object convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")` to initialize the string with | ### Return value `*this`. ### Complexity 1) linear in size of `str`. 2) linear in the size of `*this` (formally, each `CharT` has to be destroyed). If allocators do not compare equal and do not propagate, then also linear in the size of `str` (copy must be made). 3) linear in size of `s`. 4) constant. 5) linear in size of `ilist`. ### 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) | If the operation would result in `size() > max_size()`, throws `[std::length\_error](../../error/length_error "cpp/error/length error")`. | | | | --- | --- | | If an exception is thrown for any reason, this function has no effect (strong exception guarantee). | (since C++11) | ### Example ``` #include <string> #include <iostream> #include <iomanip> int main() { std::string str1; std::string str2 { "alpha" }; // (1) operator=( const basic_string& ); str1 = str2; std::cout << std::quoted(str1) << ' ' // "alpha" << std::quoted(str2) << '\n'; // "alpha" // (2) operator=( basic_string&& ); str1 = std::move(str2); std::cout << std::quoted(str1) << ' ' // "alpha" << std::quoted(str2) << '\n'; // "" or "alpha" (unspecified) // (3) operator=( const CharT* ); str1 = "beta"; std::cout << std::quoted(str1) << '\n'; // "beta" // (4) operator=( CharT ); str1 = '!'; std::cout << std::quoted(str1) << '\n'; // "!" // (5) operator=( std::initializer_list<CharT> ); str1 = {'g','a','m','m','a'}; std::cout << std::quoted(str1) << '\n'; // "gamma" // (6) operator=( const T& ); str1 = 35U; // equivalent to str1 = static_cast<char>(35U); std::cout << std::quoted(str1) << '\n'; // "#" (ASCII = 35) } ``` Possible output: ``` "alpha" "alpha" "alpha" "" "beta" "!" "gamma" "#" ``` ### 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 2063](https://cplusplus.github.io/LWG/issue2063) | C++11 | non-normative note stated that swap is a valid implementation of move assignment | corrected to support allocators | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | ### See also | | | | --- | --- | | [(constructor)](basic_string "cpp/string/basic string/basic string") | constructs a `basic_string` (public member function) | | [assign](assign "cpp/string/basic string/assign") | assign characters to a string (public member function) | | [operator=](../basic_string_view/operator= "cpp/string/basic string view/operator=") (C++17) | assigns a view (public member function of `std::basic_string_view<CharT,Traits>`) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::rend, std::basic_string<CharT,Traits,Allocator>::crend std::basic\_string<CharT,Traits,Allocator>::rend, std::basic\_string<CharT,Traits,Allocator>::crend =================================================================================================== | | | | | --- | --- | --- | | | (1) | | | ``` reverse_iterator rend(); ``` | (until C++11) | | ``` reverse_iterator rend() noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr reverse_iterator rend() noexcept; ``` | (since C++20) | | | (2) | | | ``` 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) | | | (3) | | | ``` 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 character following the last character of the reversed string. It corresponds to the character preceding the first character of the non-reversed string. This character acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value reverse iterator to the character following the last character. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <string> int main() { std::string s("A man, a plan, a canal: Panama"); { std::string c; std::copy(s.rbegin(), s.rend(), std::back_inserter(c)); std::cout << c <<'\n'; // "amanaP :lanac a ,nalp a ,nam A" } { std::string c; std::copy(s.crbegin(), s.crend(), std::back_inserter(c)); std::cout << c <<'\n'; // "amanaP :lanac a ,nalp a ,nam A" } } ``` Output: ``` amanaP :lanac a ,nalp a ,nam A amanaP :lanac a ,nalp a ,nam A ``` ### See also | | | | --- | --- | | [rbegin crbegin](rbegin "cpp/string/basic string/rbegin") (C++11) | 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::clear std::basic\_string<CharT,Traits,Allocator>::clear ================================================= | | | | | --- | --- | --- | | ``` void clear(); ``` | | (until C++11) | | ``` void clear() noexcept; ``` | | (since C++11) (until C++20) | | ``` constexpr void clear() noexcept; ``` | | (since C++20) | Removes all characters from the string as if by executing `erase(begin(), end())`. All pointers, references, and iterators are invalidated. ### Parameters (none). ### Return value (none). ### Notes Unlike for `[std::vector::clear](../../container/vector/clear "cpp/container/vector/clear")`, the C++ standard does not explicitly require that `[capacity](capacity "cpp/string/basic string/capacity")` is unchanged by this function, but existing implementations do not change capacity. This means that they do not release the allocated memory (see also `[shrink\_to\_fit](shrink_to_fit "cpp/string/basic string/shrink to fit")`). ### Complexity Linear in the size of the string, although existing implementations operate in constant time. ### Example ``` #include <cassert> #include <string> int main() { std::string s{ "Exemplar" }; std::string::size_type const capacity = s.capacity(); s.clear(); assert(s.capacity() == capacity); // <- not guaranteed assert(s.empty()); assert(s.size() == 0); } ``` ### See also | | | | --- | --- | | [erase](erase "cpp/string/basic string/erase") | removes characters (public member function) | cpp std::getline std::getline ============ | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& getline( std::basic_istream<CharT, Traits>& input, std::basic_string<CharT, Traits, Allocator>& str, CharT delim ); ``` | (1) | | | ``` template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& getline( std::basic_istream<CharT, Traits>&& input, std::basic_string<CharT, Traits, Allocator>& str, CharT delim ); ``` | (1) | (since C++11) | | ``` template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& getline( std::basic_istream<CharT, Traits>& input, std::basic_string<CharT, Traits, Allocator>& str ); ``` | (2) | | | ``` template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& getline( std::basic_istream<CharT, Traits>&& input, std::basic_string<CharT, Traits, Allocator>& str ); ``` | (2) | (since C++11) | `getline` reads characters from an input stream and places them into a string: 1) Behaves as [UnformattedInputFunction](../../named_req/unformattedinputfunction "cpp/named req/UnformattedInputFunction"), except that `input.gcount()` is not affected. After constructing and checking the sentry object, performs the following: 1) Calls `str.erase()` 2) Extracts characters from `input` and appends them to `str` until one of the following occurs (checked in the order listed) a) end-of-file condition on `input`, in which case, `getline` sets [`eofbit`](../../io/ios_base/iostate "cpp/io/ios base/iostate"). b) the next available input character is `delim`, as tested by `Traits::eq(c, delim)`, in which case the delimiter character is extracted from `input`, but is not appended to `str`. c) `str.max_size()` characters have been stored, in which case `getline` sets [`failbit`](../../io/ios_base/iostate "cpp/io/ios base/iostate") and returns. 3) If no characters were extracted for whatever reason (not even the discarded delimiter), `getline` sets [`failbit`](../../io/ios_base/iostate "cpp/io/ios base/iostate") and returns. 2) Same as `getline(input, str, input.widen('\n'))`, that is, the default delimiter is the endline character. ### Parameters | | | | | --- | --- | --- | | input | - | the stream to get data from | | str | - | the string to put the data into | | delim | - | the delimiter character | ### Return value `input`. ### Notes When consuming whitespace-delimited input (e.g. `int n; [std::cin](http://en.cppreference.com/w/cpp/io/cin) >> n;`) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with `getline` will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include: * An explicit extraneous initial call to `getline` * Removing consecutive whitespace with `[std::cin](http://en.cppreference.com/w/cpp/io/cin) >> [std::ws](http://en.cppreference.com/w/cpp/io/manip/ws)` * Ignoring all leftover characters on the line of input with `cin.ignore([std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<[std::streamsize](http://en.cppreference.com/w/cpp/io/streamsize)>::max(), '\n');` ### Example The following example demonstrates how to use `getline` function to read user's input and how to process file line by line. ``` #include <string> #include <iostream> #include <sstream> int main() { // greet the user std::string name; std::cout << "What is your name? "; std::getline(std::cin, name); std::cout << "Hello " << name << ", nice to meet you.\n"; // read file line by line std::istringstream input; input.str("1\n2\n3\n4\n5\n6\n7\n"); int sum = 0; for (std::string line; std::getline(input, line); ) sum += std::stoi(line); std::cout << "\nThe sum is " << sum << ".\n\n"; // use separator to read parts of the line std::istringstream input2; input2.str("a;b;c;d"); for (std::string line; std::getline(input2, line, ';'); ) std::cout << line << '\n'; } ``` Possible output: ``` What is your name? John Q. Public Hello John Q. Public, nice to meet you. The sum is 28. a b c d ``` ### 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 91](https://cplusplus.github.io/LWG/issue91) | C++98 | `getline` did not behave as an unformatted input function | behaves as an unformatted input function | ### See also | | | | --- | --- | | [getline](../../io/basic_istream/getline "cpp/io/basic istream/getline") | extracts characters until the given character is found (public member function of `std::basic_istream<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::push_back std::basic\_string<CharT,Traits,Allocator>::push\_back ====================================================== | | | | | --- | --- | --- | | ``` void push_back( CharT ch ); ``` | | (until C++20) | | ``` constexpr void push_back( CharT ch ); ``` | | (since C++20) | Appends the given character `ch` to the end of the string. ### Parameters | | | | | --- | --- | --- | | ch | - | the character to append | ### Return value (none). ### Complexity Amortized constant. ### Exceptions If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11). If the operation would result in `size() > max_size()`, throws `[std::length\_error](../../error/length_error "cpp/error/length error")`. ### Example ``` #include <cassert> #include <string> #include <iomanip> #include <iostream> int main() { std::string str{"Short string"}; std::cout << "before=" << std::quoted(str) << '\n'; assert(str.size() == 12); str.push_back('!'); std::cout << " after=" << quoted(str) << '\n'; assert(str.size() == 13); } ``` Output: ``` before="Short string" after="Short string!" ``` ### 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 | (1) the description was missing in the C++ standard(2) the parameter type was `const CharT` | (1) description added(2) changed to `CharT` | ### See also | | | | --- | --- | | [pop\_back](pop_back "cpp/string/basic string/pop back") (C++11) | removes the last character (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::copy std::basic\_string<CharT,Traits,Allocator>::copy ================================================ | | | | | --- | --- | --- | | ``` size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const; ``` | | (until C++20) | | ``` constexpr size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const; ``` | | (since C++20) | Copies a substring `[pos, pos+count)` to character string pointed to by `dest`. If the requested substring lasts past the end of the string, or if `count == npos`, the copied substring is `[pos, size())`. The resulting character string is not null-terminated. If `pos > size()`, `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the destination character string | | count | - | length of the substring | | pos | - | position of the first character to include | ### Return value number of characters copied. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > size()`. ### Complexity linear in `count`. ### Example ``` #include <string> #include <iostream> int main() { std::string foo("quuuux"); char bar[7]{}; foo.copy(bar, sizeof bar); std::cout << bar << '\n'; } ``` Output: ``` quuuux ``` ### See also | | | | --- | --- | | [substr](substr "cpp/string/basic string/substr") | returns a substring (public member function) | | [copy](../basic_string_view/copy "cpp/string/basic string view/copy") (C++17) | copies characters (public member function of `std::basic_string_view<CharT,Traits>`) | | [copycopy\_if](../../algorithm/copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [memcpy](../byte/memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) | cpp std::basic_string<CharT,Traits,Allocator>::find_first_not_of std::basic\_string<CharT,Traits,Allocator>::find\_first\_not\_of ================================================================ | | | | | --- | --- | --- | | | (1) | | | ``` size_type find_first_not_of( const basic_string& str, size_type pos = 0 ) const; ``` | (until C++11) | | ``` size_type find_first_not_of( const basic_string& str, size_type pos = 0 ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_first_not_of( const basic_string& str, size_type pos = 0 ) const noexcept; ``` | (since C++20) | | | (2) | | | ``` size_type find_first_not_of( const CharT* s, size_type pos, size_type count ) const; ``` | (until C++20) | | ``` constexpr size_type find_first_not_of( const CharT* s, size_type pos, size_type count ) const; ``` | (since C++20) | | | (3) | | | ``` size_type find_first_not_of( const CharT* s, size_type pos = 0 ) const; ``` | (until C++20) | | ``` constexpr size_type find_first_not_of( const CharT* s, size_type pos = 0 ) const; ``` | (since C++20) | | | (4) | | | ``` size_type find_first_not_of( CharT ch, size_type pos = 0 ) const; ``` | (until C++11) | | ``` size_type find_first_not_of( CharT ch, size_type pos = 0 ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_first_not_of( CharT ch, size_type pos = 0 ) const noexcept; ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > size_type find_first_not_of( const StringViewLike& t, size_type pos = 0 ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr size_type find_first_not_of( const StringViewLike& t, size_type pos = 0 ) const noexcept(/* see below */); ``` | (since C++20) | Finds the first character equal to none of the characters in the given character sequence. The search considers only the interval [`pos`, `[size()](size "cpp/string/basic string/size")`). If the character is not present in the interval, `[npos](npos "cpp/string/basic string/npos")` will be returned. 1) Finds the first character equal to none of characters in `str`. 2) Finds the first character equal to none of characters in range `[s, s+count)`. This range can include null characters. 3) Finds the first character equal to none of characters in character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 4) Finds the first character not equal to `ch`. 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then finds the first character equal to none of characters in `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. In all cases, equality is checked by calling [`Traits::eq`](../char_traits/cmp "cpp/string/char traits/cmp"). ### Parameters | | | | | --- | --- | --- | | str | - | string identifying characters to search for | | pos | - | position for the search to start from | | count | - | length of character string identifying characters to search for | | s | - | pointer to a character string identifying characters to search for | | ch | - | character identifying characters to search for | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) identifying characters to search for | ### Return value Position of the found character or `[npos](npos "cpp/string/basic string/npos")` if no such character is found. ### Exceptions 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>)` ### Example ``` #include <string> #include <iostream> int main() { std::string to_search = "Some data with %MACROS to substitute"; std::cout << "Before: " << to_search << '\n'; auto pos = std::string::npos; while ((pos = to_search.find('%')) != std::string::npos) { // Permit uppercase letters, lowercase letters and numbers in macro names const auto after = to_search.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789", pos + 1); // Now to_search[pos] == '%' and to_search[after] == ' ' (after the 'S') if(after != std::string::npos) to_search.replace(pos, after - pos, "some very nice macros"); } std::cout << "After: " << to_search << '\n'; } ``` Output: ``` Before: Some data with %MACROS to substitute After: Some data with some very nice macros to substitute ``` ### 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 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | overload (3) and (4) were noexcept | removed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++11C++17 | noexcept for overload (4)/(5) was accidently dropped by LWG2064/LWG2946 | restored | ### See also | | | | --- | --- | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [rfind](rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function) | | [find\_first\_of](find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function) | | [find\_last\_of](find_last_of "cpp/string/basic string/find last of") | find last occurrence of characters (public member function) | | [find\_last\_not\_of](find_last_not_of "cpp/string/basic string/find last not of") | find last absence 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 of `std::basic_string_view<CharT,Traits>`) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::find_first_of std::basic\_string<CharT,Traits,Allocator>::find\_first\_of =========================================================== | | | | | --- | --- | --- | | | (1) | | | ``` size_type find_first_of( const basic_string& str, size_type pos = 0 ) const; ``` | (until C++11) | | ``` size_type find_first_of( const basic_string& str, size_type pos = 0 ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_first_of( const basic_string& str, size_type pos = 0 ) const noexcept; ``` | (since C++20) | | | (2) | | | ``` size_type find_first_of( const CharT* s, size_type pos, size_type count ) const; ``` | (until C++20) | | ``` constexpr size_type find_first_of( const CharT* s, size_type pos, size_type count ) const; ``` | (since C++20) | | | (3) | | | ``` size_type find_first_of( const CharT* s, size_type pos = 0 ) const; ``` | (until C++20) | | ``` constexpr size_type find_first_of( const CharT* s, size_type pos = 0 ) const; ``` | (since C++20) | | | (4) | | | ``` size_type find_first_of( CharT ch, size_type pos = 0 ) const; ``` | (until C++11) | | ``` size_type find_first_of( CharT ch, size_type pos = 0 ) const noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr size_type find_first_of( CharT ch, size_type pos = 0 ) const noexcept; ``` | (since C++20) | | | (5) | | | ``` template < class StringViewLike > size_type find_first_of( const StringViewLike& t, size_type pos = 0 ) const noexcept(/* see below */); ``` | (since C++17) (until C++20) | | ``` template < class StringViewLike > constexpr size_type find_first_of( const StringViewLike& t, size_type pos = 0 ) const noexcept(/* see below */); ``` | (since C++20) | Finds the first character equal to one of the characters in the given character sequence. The search considers only the interval [`pos`, `[size()](size "cpp/string/basic string/size")`). If the character is not present in the interval, `[npos](npos "cpp/string/basic string/npos")` will be returned. 1) Finds the first character equal to one of the characters in `str`. 2) Finds the first character equal to one of the characters in the range `[s, s+count)`. This range can include null characters. 3) Finds the first character equal to one of the characters in character string pointed to by `s`. The length of the string is determined by the first null character using `Traits::length(s)`. 4) Finds the first character equal to `ch`. 5) Implicitly converts `t` to a string view `sv` as if by `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits> sv = t;`, then finds the first character equal to one of the characters in `sv`. This overload participates in overload resolution only if `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>` is `true` and `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const StringViewLike&, const CharT\*>` is `false`. ### Parameters | | | | | --- | --- | --- | | str | - | string identifying characters to search for | | pos | - | position at which to begin searching | | count | - | length of character string identifying characters to search for | | s | - | pointer to a character string identifying characters to search for | | ch | - | character to search for | | t | - | object (convertible to `[std::basic\_string\_view](../basic_string_view "cpp/string/basic string view")`) identifying characters to search for | ### Return value Position of the found character or `[npos](npos "cpp/string/basic string/npos")` if no such character is found. ### Exceptions 5) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<const T&, [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<CharT, Traits>>)` ### Notes `Traits::eq()` is used to perform the comparison. ### Example ``` #include <cassert> #include <iostream> #include <string> #include <string_view> int main() { using namespace std::string_literals; std::string::size_type sz; // (1) sz = "alignas"s.find_first_of("klmn"s); // └────────────────────────┘ assert(sz == 1); sz = "alignof"s.find_first_of("wxyz"s); // assert(sz == std::string::npos); // (2) const char* buf = "xyzabc"; sz = "consteval"s.find_first_of(buf, 0, 3); // assert(sz == std::string::npos); sz = "consteval"s.find_first_of(buf, 0, 6); // └─────────────────────────┘c in buf assert(sz == 0); // (3) sz = "decltype"s.find_first_of(buf); // └──────────────────────┘c in buf assert(sz == 2); // (4) sz = "co_await"s.find_first_of('a'); // └──────────────────────┘ assert(sz == 3); // (5) std::string_view sv{"int"}; sz = "constinit"s.find_first_of(sv); // └───────────────────────┘n in sv assert(sz == 2); std::cout << "All tests passed.\n"; } ``` Possible output: ``` All tests passed. ``` ### 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 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | overload (3) and (4) were noexcept | removed | | [LWG 2946](https://cplusplus.github.io/LWG/issue2946) | C++17 | `string_view` overload causes ambiguity in some cases | avoided by making it a template | | [P1148R0](https://wg21.link/P1148R0) | C++11C++17 | noexcept for overload (4)/(5) was accidently dropped by LWG2064/LWG2946 | restored | ### See also | | | | --- | --- | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [rfind](rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function) | | [find\_first\_not\_of](find_first_not_of "cpp/string/basic string/find first not of") | find first absence of characters (public member function) | | [find\_last\_of](find_last_of "cpp/string/basic string/find last of") | find last occurrence of characters (public member function) | | [find\_last\_not\_of](find_last_not_of "cpp/string/basic string/find last not of") | find last absence of characters (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 of `std::basic_string_view<CharT,Traits>`) | | [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) | cpp std::basic_string<CharT,Traits,Allocator>::substr std::basic\_string<CharT,Traits,Allocator>::substr ================================================== | | | | | --- | --- | --- | | ``` basic_string substr( size_type pos = 0, size_type count = npos ) const; ``` | | (until C++20) | | ``` constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const; ``` | | (since C++20) | Returns a substring `[pos, pos+count)`. If the requested substring extends past the end of the string, i.e. the `count` is greater than `size() - pos` (e.g. if `count == npos`), the returned substring is `[pos, [size()](size "cpp/string/basic string/size"))`. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the first character to include | | count | - | length of the substring | ### Return value String containing the substring `[pos, pos+count)` or `[pos, [size()](size "cpp/string/basic string/size"))`. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `pos > [size()](size "cpp/string/basic string/size")`. ### Complexity Linear in `count`. ### Notes The returned string is constructed as if by `basic_string(data()+pos, count)`, which implies that the returned string's allocator will be default-constructed — the new allocator might *not* be a copy of `this->[get\_allocator()](get_allocator "cpp/string/basic string/get allocator")`. ### Example ``` #include <string> #include <iostream> int main() { std::string a = "0123456789abcdefghij"; // count is npos, returns [pos, size()) std::string sub1 = a.substr(10); std::cout << sub1 << '\n'; // both pos and pos+count are within bounds, returns [pos, pos+count) std::string sub2 = a.substr(5, 3); std::cout << sub2 << '\n'; // pos is within bounds, pos+count is not, returns [pos, size()) std::string sub4 = a.substr(a.size()-3, 50); // this is effectively equivalent to // std::string sub4 = a.substr(17, 3); // since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3 std::cout << sub4 << '\n'; try { // pos is out of bounds, throws std::string sub5 = a.substr(a.size()+3, 50); std::cout << sub5 << '\n'; } catch(const std::out_of_range& e) { std::cout << "pos exceeds string size\n"; } } ``` Output: ``` abcdefghij 567 hij pos exceeds string size ``` ### See also | | | | --- | --- | | [copy](copy "cpp/string/basic string/copy") | copies characters (public member function) | | [sizelength](size "cpp/string/basic string/size") | returns the number of characters (public member function) | | [find](find "cpp/string/basic string/find") | find characters in the string (public member function) | | [npos](npos "cpp/string/basic string/npos") [static] | special value. The exact meaning depends on the context (public static member constant) | cpp operator==,!=,<,<=,>,>=,<=>(std::basic_string) operator==,!=,<,<=,>,>=,<=>(std::basic\_string) =============================================== | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | Compare two `basic_string` objects | | | | | (1) | | | ``` template< class CharT, class Traits, class Alloc > bool operator==( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > bool operator==( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++11) (until C++20) | | ``` template< class CharT, class Traits, class Alloc > constexpr bool operator==( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++20) | | | (2) | | | ``` template< class CharT, class Traits, class Alloc > bool operator!=( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > bool operator!=( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++11) (until C++20) | | | (3) | | | ``` template< class CharT, class Traits, class Alloc > bool operator<( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > bool operator<( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++11) (until C++20) | | | (4) | | | ``` template< class CharT, class Traits, class Alloc > bool operator<=( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > bool operator<=( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++11) (until C++20) | | | (5) | | | ``` template< class CharT, class Traits, class Alloc > bool operator>( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > bool operator>( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++11) (until C++20) | | | (6) | | | ``` template< class CharT, class Traits, class Alloc > bool operator>=( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++11) | | ``` template< class CharT, class Traits, class Alloc > bool operator>=( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (since C++11) (until C++20) | | ``` template< class CharT, class Traits, class Alloc > constexpr /*comp-cat*/ operator<=>( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ) noexcept; ``` | (7) | (since C++20) | | Compare a `basic_string` object and null-terminated array of `T` | | | | | (8) | | | ``` template< class CharT, class Traits, class Alloc > bool operator==( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > constexpr bool operator==( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (since C++20) | | ``` template< class CharT, class Traits, class Alloc > bool operator==( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++20) | | | (9) | | | ``` template< class CharT, class Traits, class Alloc > bool operator!=( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > bool operator!=( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++20) | | | (10) | | | ``` template< class CharT, class Traits, class Alloc > bool operator<( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > bool operator<( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++20) | | | (11) | | | ``` template< class CharT, class Traits, class Alloc > bool operator<=( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > bool operator<=( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++20) | | | (12) | | | ``` template< class CharT, class Traits, class Alloc > bool operator>( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > bool operator>( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++20) | | | (13) | | | ``` template< class CharT, class Traits, class Alloc > bool operator>=( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > bool operator>=( const CharT* lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); ``` | (until C++20) | | ``` template< class CharT, class Traits, class Alloc > constexpr /*comp-cat*/ operator<=>( const std::basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); ``` | (14) | (since C++20) | Compares the contents of a string with another string or a null-terminated array of `CharT`. All comparisons are done via the `[compare()](compare "cpp/string/basic string/compare")` member function (which itself is defined in terms of `Traits::compare()`): * Two strings are equal if both the size of `lhs` and `rhs` are equal and each character in `lhs` has equivalent character in `rhs` at the same position. * The ordering comparisons are done lexicographically -- the comparison is performed by a function equivalent to `[std::lexicographical\_compare](../../algorithm/lexicographical_compare "cpp/algorithm/lexicographical compare")` or `[std::lexicographical\_compare\_three\_way](../../algorithm/lexicographical_compare_three_way "cpp/algorithm/lexicographical compare three way")` (since C++20). 1-7) Compares two `basic_string` objects. 8-14) Compares a `basic_string` object and a null-terminated array of `CharT`. | | | | --- | --- | | The return type of three-way comparison operators (`/*comp-cat*/`) is `Traits::comparison_category` if that qualified-id exists and denotes a type, `std::weak_ordering` otherwise. If `/*comp-cat*/` is not a comparison category type, the program is ill-formed. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | strings whose contents to compare | ### Return value 1-6,8-13) `true` if the corresponding comparison holds, `false` otherwise. 7,14) `static_cast</*comp-cat*/>(lhs.compare(rhs) <=> 0)`. ### Complexity Linear in the size of the strings. ### Notes | | | | --- | --- | | If at least one parameter is of type `[std::string](../basic_string "cpp/string/basic string")`, `[std::wstring](../basic_string "cpp/string/basic string")`, `[std::u8string](../basic_string "cpp/string/basic string")`, `[std::u16string](../basic_string "cpp/string/basic string")`, or `[std::u32string](../basic_string "cpp/string/basic string")`, the return type of `operator<=>` is `std::strong_ordering`. | (since C++20) | ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2064](https://cplusplus.github.io/LWG/issue2064) | C++11 | whether overloads taking two `basic_string`s are noexcept was inconsistent;overloads taking a `CharT*` were noexcept but might raise UB | made consistent;noexcept removed | | [LWG 3432](https://cplusplus.github.io/LWG/issue3432) | C++20 | the return type of `operator<=>` was not required to be a comparison category type | required | cpp std::stof, std::stod, std::stold std::stof, std::stod, std::stold ================================ | Defined in header `[<string>](../../header/string "cpp/header/string")` | | | | --- | --- | --- | | ``` float stof( const std::string& str, std::size_t* pos = nullptr ); float stof( const std::wstring& str, std::size_t* pos = nullptr ); ``` | (1) | (since C++11) | | ``` double stod( const std::string& str, std::size_t* pos = nullptr ); double stod( const std::wstring& str, std::size_t* pos = nullptr ); ``` | (2) | (since C++11) | | ``` long double stold( const std::string& str, std::size_t* pos = nullptr ); long double stold( const std::wstring& str, std::size_t* pos = nullptr ); ``` | (3) | (since C++11) | Interprets a floating point value in a string `str`. 1) calls `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)(str.c\_str(), &ptr)` or `[std::wcstof](http://en.cppreference.com/w/cpp/string/wide/wcstof)(str.c\_str(), &ptr)` 2) calls `[std::strtod](http://en.cppreference.com/w/cpp/string/byte/strtof)(str.c\_str(), &ptr)` or `[std::wcstod](http://en.cppreference.com/w/cpp/string/wide/wcstof)(str.c\_str(), &ptr)` 3) calls `[std::strtold](http://en.cppreference.com/w/cpp/string/byte/strtof)(str.c\_str(), &ptr)` or `[std::wcstold](http://en.cppreference.com/w/cpp/string/wide/wcstof)(str.c\_str(), &ptr)` Function discards any whitespace characters (as determined by `std::isspace()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following: * decimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10) * hexadecimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + `0x` or `0X` + nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2) * infinity expression. It consists of the following parts: + (optional) plus or minus sign + `INF` or `INFINITY` ignoring case * not-a-number expression. It consists of the following parts: + (optional) plus or minus sign + `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value. * any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "cpp/locale/setlocale") If `pos` is not a null pointer, then a pointer `ptr`, internal to the conversion functions, will receive the address of the first unconverted character in `str.c_str()`, and the index of that character will be calculated and stored in `*pos`, giving the number of characters that were processed by the conversion. ### Parameters | | | | | --- | --- | --- | | str | - | the string to convert | | pos | - | address of an integer to store the number of characters processed | ### Return value The string converted to the specified floating point type. ### Exceptions `[std::invalid\_argument](../../error/invalid_argument "cpp/error/invalid argument")` if no conversion could be performed. `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if the converted value would fall out of the range of the result type or if the underlying function (`strtof`, `strtod` or `strtold`) sets `errno` to `[ERANGE](http://en.cppreference.com/w/cpp/error/errno_macros)`. ### 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 2403](https://cplusplus.github.io/LWG/issue2403) | C++11 | `stof` called `[std::strtod](../byte/strtof "cpp/string/byte/strtof")` or `[std::wcstod](../wide/wcstof "cpp/string/wide/wcstof")` | `stof` calls `[std::strtof](../byte/strtof "cpp/string/byte/strtof")` or `[std::wcstof](../wide/wcstof "cpp/string/wide/wcstof")` | ### See also | | | | --- | --- | | [stoistolstoll](stol "cpp/string/basic string/stol") (C++11)(C++11)(C++11) | converts a string to a signed integer (function) | | [stoulstoull](stoul "cpp/string/basic string/stoul") (C++11)(C++11) | converts a string to an unsigned integer (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) |
programming_docs
cpp std::basic_string<CharT,Traits,Allocator>::reserve std::basic\_string<CharT,Traits,Allocator>::reserve =================================================== | | | | | --- | --- | --- | | | (1) | | | ``` void reserve( size_type new_cap = 0 ); ``` | (until C++20) | | ``` constexpr void reserve( size_type new_cap ); ``` | (since C++20) | | ``` void reserve(); ``` | (2) | (since C++20) (deprecated) | 1) Informs a `std::basic_string` object of a planned change in size, so that it can manage the storage allocation appropriately. * If `new_cap` is greater than the current `[capacity()](capacity "cpp/string/basic string/capacity")`, new storage is allocated, and `[capacity()](capacity "cpp/string/basic string/capacity")` is made equal or greater than `new_cap`. | | | | --- | --- | | * If `new_cap` is less than the current `[capacity()](capacity "cpp/string/basic string/capacity")`, this is a non-binding shrink request. * If `new_cap` is less than the current `[size()](size "cpp/string/basic string/size")`, this is a non-binding shrink-to-fit request equivalent to `[shrink\_to\_fit()](shrink_to_fit "cpp/string/basic string/shrink to fit")` (since C++11). | (until C++20) | | * If `new_cap` is less than or equal to the current `[capacity()](capacity "cpp/string/basic string/capacity")`, there is no effect. | (since C++20) | If a capacity change takes place, all iterators and references, including the past-the-end iterator, are invalidated. | | | | --- | --- | | 2) A call to `reserve` with no argument is a non-binding shrink-to-fit request. After this call, `[capacity()](capacity "cpp/string/basic string/capacity")` has an unspecified value greater than or equal to `[size()](size "cpp/string/basic string/size")`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | new\_cap | - | new capacity of the string | ### Return value (none). ### Exceptions Throws `[std::length\_error](../../error/length_error "cpp/error/length error")` if `new_cap` is greater than `[max\_size()](max_size "cpp/string/basic string/max size")`. May throw any exceptions thrown by `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::allocate()`, such as `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")`. ### Complexity At most linear in the `[size()](size "cpp/string/basic string/size")` of the string. ### Example ``` #include <cassert> #include <iostream> #include <string> int main() { std::string s; const std::string::size_type new_capacity{ 100u }; std::cout << "Before: " << s.capacity() << "\n"; s.reserve(new_capacity); std::cout << "After: " << s.capacity() << "\n"; assert(new_capacity <= s.capacity()); // observing the capacity growth factor auto cap{ s.capacity() }; for (int check{}; check != 4; ++check) { while(cap == s.capacity()) s += '$'; cap = s.capacity(); std::cout << "New capacity: " << cap << '\n'; } // s.reserve(); //< deprecated in C++20, use: s.shrink_to_fit(); std::cout << "After: " << s.capacity() << "\n"; } ``` Possible output: ``` Before: 15 After: 100 New capacity: 200 New capacity: 400 New capacity: 800 New capacity: 1600 After: 801 ``` ### See also | | | | --- | --- | | [capacity](capacity "cpp/string/basic string/capacity") | returns the number of characters that can be held in currently allocated storage (public member function) | | [resize](resize "cpp/string/basic string/resize") | changes the number of characters stored (public member function) | cpp std::basic_string<CharT,Traits,Allocator>::empty std::basic\_string<CharT,Traits,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 string has no characters, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the string is empty, `false` otherwise. ### Complexity Constant. ### Example ``` #include <iostream> #include <string> int main() { std::string s; std::boolalpha(std::cout); std::cout << "s.empty():" << s.empty() << "\t s:'" << s << "'\n"; s = "Exemplar"; std::cout << "s.empty():" << s.empty() << "\t s:'" << s << "'\n"; s = ""; std::cout << "s.empty():" << s.empty() << "\t s:'" << s << "'\n"; } ``` Output: ``` s.empty():true s:'' s.empty():false s:'Exemplar' s.empty():true s:'' ``` ### See also | | | | --- | --- | | [sizelength](size "cpp/string/basic string/size") | returns the number of characters (public member function) | | [max\_size](max_size "cpp/string/basic string/max size") | returns the maximum number of characters (public member function) | | [capacity](capacity "cpp/string/basic string/capacity") | returns the number of characters that can be held in currently allocated storage (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [empty](../basic_string_view/empty "cpp/string/basic string view/empty") (C++17) | checks whether the view is empty (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::begin, std::basic_string<CharT,Traits,Allocator>::cbegin std::basic\_string<CharT,Traits,Allocator>::begin, std::basic\_string<CharT,Traits,Allocator>::cbegin ===================================================================================================== | | | | | --- | --- | --- | | | (1) | | | ``` iterator begin(); ``` | (until C++11) | | ``` iterator begin() noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr iterator begin() noexcept; ``` | (since C++20) | | | (2) | | | ``` 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) | | | (3) | | | ``` 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 character of the string. `begin()` returns a [mutable](../../iterator "cpp/iterator") or [constant](../../iterator "cpp/iterator") iterator, depending on the constness of `*this`. `cbegin()` always returns a [constant](../../iterator "cpp/iterator") iterator. It is equivalent to `const_cast<const basic_string&>(*this).begin()`. ![range-begin-end.svg]() ### Parameters (none). ### Return value iterator to the first character. ### Complexity Constant. ### Example ``` #include <string> #include <iostream> int main() { std::string s("Exemplar"); *s.begin() = 'e'; std::cout << s <<'\n'; auto i = s.cbegin(); std::cout << *i << '\n'; // *i = 'E'; // error: i is a constant iterator } ``` Output: ``` exemplar e ``` ### See also | | | | --- | --- | | [end cend](end "cpp/string/basic string/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../basic_string_view/begin "cpp/string/basic string view/begin") (C++17) | returns an iterator to the beginning (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::end, std::basic_string<CharT,Traits,Allocator>::cend std::basic\_string<CharT,Traits,Allocator>::end, std::basic\_string<CharT,Traits,Allocator>::cend ================================================================================================= | | | | | --- | --- | --- | | | (1) | | | ``` iterator end(); ``` | (until C++11) | | ``` iterator end() noexcept; ``` | (since C++11) (until C++20) | | ``` constexpr iterator end() noexcept; ``` | (since C++20) | | | (2) | | | ``` 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) | | | (3) | | | ``` 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 character following the last character of the string. This character acts as a placeholder, attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value iterator to the character following the last character. ### Complexity Constant. ### Example ``` #include <iostream> #include <algorithm> #include <iterator> #include <string> int main() { std::string s("Exemparl"); std::next_permutation(s.begin(), s.end()); std::string c; std::copy(s.cbegin(), s.cend(), std::back_inserter(c)); std::cout << c <<'\n'; // "Exemplar" } ``` Output: ``` Exemplar ``` ### See also | | | | --- | --- | | [begincbegin](begin "cpp/string/basic string/begin") (C++11) | 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 of `std::basic_string_view<CharT,Traits>`) | cpp std::basic_string<CharT,Traits,Allocator>::pop_back std::basic\_string<CharT,Traits,Allocator>::pop\_back ===================================================== | | | | | --- | --- | --- | | ``` void pop_back(); ``` | | (since C++11) (until C++20) | | ``` constexpr void pop_back(); ``` | | (since C++20) | Removes the last character from the string. Equivalent to `erase(end()-1)`. The behavior is undefined if the string is empty. ### Parameters (none). ### Return value (none). ### Complexity Constant. ### Exceptions Throws nothing. ### Example ``` #include <cassert> #include <string> #include <iomanip> #include <iostream> int main() { std::string str("Short string!"); std::cout << "before=" << quoted(str) << '\n'; assert(str.size() == 13); str.pop_back(); std::cout << " after=" << quoted(str) << '\n'; assert(str.size() == 12); str.clear(); // str.pop_back(); // UB! } ``` Output: ``` before="Short string!" after="Short string" ``` ### See also | | | | --- | --- | | [push\_back](push_back "cpp/string/basic string/push back") | appends a character to the end (public member function) | | [erase](erase "cpp/string/basic string/erase") | removes characters (public member function) | cpp std::strncat std::strncat ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` char *strncat( char *dest, const char *src, std::size_t count ); ``` | | | Appends a byte string pointed to by `src` to a byte string pointed to by `dest`. At most `count` characters are copied. The resulting byte string is null-terminated. The destination byte string must have enough space for the contents of both `dest` and `src` plus the terminating null character, except that the size of `src` is limited to `count`. The behavior is undefined if the strings overlap. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated byte string to append to | | src | - | pointer to the null-terminated byte string to copy from | | count | - | maximum number of characters to copy | ### Return value `dest`. ### Notes Because `strncat` needs to seek to the end of `dest` on each call, it is inefficient to concatenate many strings into one using `strncat`. ### Example ``` #include <cstring> #include <cstdio> int main() { char str[50] = "Hello "; char str2[50] = "World!"; std::strcat(str, str2); std::strncat(str, " Goodbye World!", 3); std::puts(str); } ``` Output: ``` Hello World! Go ``` ### See also | | | | --- | --- | | [strcat](strcat "cpp/string/byte/strcat") | concatenates two strings (function) | | [strcpy](strcpy "cpp/string/byte/strcpy") | copies one string to another (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strncat "c/string/byte/strncat") for `strncat` | cpp std::strchr std::strchr =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` const char* strchr( const char* str, int ch ); ``` | | | | ``` char* strchr( char* str, int ch ); ``` | | | Finds the first occurrence of the character `static_cast<char>(ch)` in the byte string pointed to by `str`. The terminating null character is considered to be a part of the string and can be found if searching for `'\0'`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be analyzed | | ch | - | 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 <cstring> int main() { const char *str = "Try not. Do, or do not. There is no try."; char target = 'T'; const char *result = str; while ((result = std::strchr(result, target)) != nullptr) { std::cout << "Found '" << target << "' starting at '" << result << "'\n"; // Increment result, otherwise we'll find target at the same location ++result; } } ``` Output: ``` Found 'T' starting at 'Try not. Do, or do not. There is no try.' Found 'T' starting at 'There is no try.' ``` ### See also | | | | --- | --- | | [memchr](memchr "cpp/string/byte/memchr") | searches an array for the first occurrence of a character (function) | | [find](../basic_string/find "cpp/string/basic string/find") | find characters in the string (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [wcschr](../wide/wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) | | [strrchr](strrchr "cpp/string/byte/strrchr") | finds the last occurrence of a character (function) | | [strpbrk](strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strchr "c/string/byte/strchr") for `strchr` | cpp std::isxdigit std::isxdigit ============= | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isxdigit( int ch ); ``` | | | Checks if the given character is a hexadecimal numeric character (`0123456789abcdefABCDEF`). The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is an hexadecimal numeric character, zero otherwise. ### Notes `isdigit` and `isxdigit` are the only standard narrow character classification functions that are not affected by the currently installed C locale. although some implementations (e.g. Microsoft in 1252 codepage) may classify additional single-byte characters as digits. Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isxdigit` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isxdigit(char ch) { return std::isxdigit(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_xdigits(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isxdigit) // wrong // [](int c){ return std::isxdigit(c); } // wrong // [](char c){ return std::isxdigit(c); } // wrong [](unsigned char c){ return std::isxdigit(c); } // correct ); } ``` ### See also | | | | --- | --- | | [isxdigit(std::locale)](../../locale/isxdigit "cpp/locale/isxdigit") | checks if a character is classified as a hexadecimal digit by a locale (function template) | | [iswxdigit](../wide/iswxdigit "cpp/string/wide/iswxdigit") | checks if a character is a hexadecimal character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isxdigit "c/string/byte/isxdigit") for `isxdigit` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | **`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`** |
programming_docs
cpp std::toupper std::toupper ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int toupper( int ch ); ``` | | | Converts the given character to uppercase according to the character conversion rules defined by the currently installed C locale. In the default "C" locale, the following lowercase letters `abcdefghijklmnopqrstuvwxyz` are replaced with respective uppercase letters `ABCDEFGHIJKLMNOPQRSTUVWXYZ`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to be converted. If the value of `ch` is not representable as `unsigned char` and does not equal `[EOF](http://en.cppreference.com/w/cpp/io/c)`, the behavior is undefined. | ### Return value Converted character or `ch` if no uppercase version is defined by the current C locale. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::toupper` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` char my_toupper(char ch) { return static_cast<char>(std::toupper(static_cast<unsigned char>(ch))); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` std::string str_toupper(std::string s) { std::transform(s.begin(), s.end(), s.begin(), // static_cast<int(*)(int)>(std::toupper) // wrong // [](int c){ return std::toupper(c); } // wrong // [](char c){ return std::toupper(c); } // wrong [](unsigned char c){ return std::toupper(c); } // correct ); return s; } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xb8'; // the character ž in ISO-8859-15 // but ¸ (cedilla) in ISO-8859-1 std::setlocale(LC_ALL, "en_US.iso88591"); std::cout << std::hex << std::showbase; std::cout << "in iso8859-1, toupper('0xb8') gives " << std::toupper(c) << '\n'; std::setlocale(LC_ALL, "en_US.iso885915"); std::cout << "in iso8859-15, toupper('0xb8') gives " << std::toupper(c) << '\n'; } ``` Output: ``` in iso8859-1, toupper('0xb8') gives 0xb8 in iso8859-15, toupper('0xb8') gives 0xb4 ``` ### See also | | | | --- | --- | | [tolower](tolower "cpp/string/byte/tolower") | converts a 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) | | [towupper](../wide/towupper "cpp/string/wide/towupper") | converts a wide character to uppercase (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/toupper "c/string/byte/toupper") for `toupper` | cpp std::strstr std::strstr =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` const char* strstr( const char* haystack, const char* needle ); ``` | | | | ``` char* strstr( char* haystack, const char* needle ); ``` | | | Finds the first occurrence of the byte string `needle` in the byte string pointed to by `haystack`. The terminating null characters are not compared. ### Parameters | | | | | --- | --- | --- | | haystack | - | pointer to the null-terminated byte string to examine | | needle | - | pointer to the null-terminated byte string to search for | ### Return value Pointer to the first character of the found substring in `haystack`, or a null pointer if no such character is found. If `needle` points to an empty string, `haystack` is returned. ### Example ``` #include <iostream> #include <cstring> int main() { const char *str = "Try not. Do, or do not. There is no try."; const char *target = "not"; const char *result = str; while ((result = std::strstr(result, target)) != nullptr) { std::cout << "Found '" << target << "' starting at '" << result << "'\n"; // Increment result, otherwise we'll find target at the same location ++result; } } ``` Output: ``` Found 'not' starting at 'not. Do, or do not. There is no try.' Found 'not' starting at 'not. There is no try.' ``` ### 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>`) | | [wcsstr](../wide/wcsstr "cpp/string/wide/wcsstr") | finds the first occurrence of a wide string within another wide string (function) | | [strchr](strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) | | [strrchr](strrchr "cpp/string/byte/strrchr") | finds the last occurrence of a character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strstr "c/string/byte/strstr") for `strstr` | cpp std::memset std::memset =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` void* memset( void* dest, int ch, std::size_t count ); ``` | | | Copies the value `static_cast<unsigned char>(ch)` into each of the first `count` characters of the object pointed to by `dest`. If the object is a [potentially-overlapping subobject](../../language/object#Subobjects "cpp/language/object") or is not [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behavior is undefined. If `count` is greater than the size of the object pointed to by `dest`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the object to fill | | ch | - | fill byte | | count | - | number of bytes to fill | ### Return value `dest`. ### Notes `std::memset` may be optimized away (under the [as-if](../../language/as_if "cpp/language/as if") rules) if the object modified by this function is not accessed again for the rest of its lifetime (e.g., [gcc bug 8537](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8537)). For that reason, this function cannot be used to scrub memory (e.g., to fill an array that stored a password with zeroes). Solutions for that include [`std::fill`](../../algorithm/fill "cpp/algorithm/fill") with volatile pointers, C11 [`memset_s`](https://en.cppreference.com/w/c/string/byte/memset "c/string/byte/memset"), FreeBSD [explicit\_bzero](https://www.freebsd.org/cgi/man.cgi?query=explicit_bzero) or Microsoft [`SecureZeroMemory`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa366877.aspx). ### Example ``` #include <bitset> #include <climits> #include <cstring> #include <iostream> int main() { int a[4]; using bits = std::bitset<sizeof(int)*CHAR_BIT>; std::memset(a, 0b1111'0000'0011, sizeof a); for (int ai : a) std::cout << bits(ai) << '\n'; } ``` Output: ``` 00000011000000110000001100000011 00000011000000110000001100000011 00000011000000110000001100000011 00000011000000110000001100000011 ``` ### See also | | | | --- | --- | | [memcpy](memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) | | [memmove](memmove "cpp/string/byte/memmove") | moves one buffer to another (function) | | [wmemset](../wide/wmemset "cpp/string/wide/wmemset") | copies the given wide character to every position in a wide character array (function) | | [fill](../../algorithm/fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [fill\_n](../../algorithm/fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) | | [is\_trivially\_copyable](../../types/is_trivially_copyable "cpp/types/is trivially copyable") (C++11) | checks if a type is trivially copyable (class template) | | [C documentation](https://en.cppreference.com/w/c/string/byte/memset "c/string/byte/memset") for `memset` | cpp std::memcmp std::memcmp =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` int memcmp( const void* lhs, const void* rhs, std::size_t count ); ``` | | | Reinterprets the objects pointed to by `lhs` and `rhs` as arrays of `unsigned char` and compares the first `count` bytes of these arrays. The comparison is done lexicographically. The sign of the result is the sign of the difference between the values of the first pair of bytes (both interpreted as `unsigned char`) that differ in the objects being compared. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pointers to the memory buffers to compare | | count | - | number of bytes to examine | ### Return value Negative value if the first differing byte (reinterpreted as `unsigned char`) in `lhs` is less than the corresponding byte in `rhs`. `​0​` if all `count` bytes of `lhs` and `rhs` are equal. Positive value if the first differing byte in `lhs` is greater than the corresponding byte in `rhs`. ### Notes This function reads [object representations](../../language/object "cpp/language/object"), not the object values, and is typically meaningful for only trivially-copyable objects that have no padding. For example, `memcmp()` between two objects of type `[std::string](../basic_string "cpp/string/basic string")` or `[std::vector](../../container/vector "cpp/container/vector")` will not compare their contents, and `memcmp()` between two objects of type `struct{char c; int n;}` will compare the padding bytes whose values may differ when the values of `c` and `n` are the same. ### Example ``` #include <iostream> #include <cstring> void demo(const char* lhs, const char* rhs, std::size_t sz) { std::cout << std::string(lhs, sz); const int rc = std::memcmp(lhs, rhs, sz); if(rc < 0) std::cout << " precedes "; else if(rc > 0) std::cout << " follows "; else std::cout << " compares equal to "; std::cout << std::string(rhs, sz) << " in lexicographical order\n"; } int main() { char a1[] = {'a','b','c'}; char a2[sizeof a1] = {'a','b','d'}; demo(a1, a2, sizeof a1); demo(a2, a1, sizeof a1); demo(a1, a1, sizeof a1); } ``` Output: ``` abc precedes abd in lexicographical order abd follows abc in lexicographical order abc compares equal to abc in lexicographical order ``` ### See also | | | | --- | --- | | [strcmp](strcmp "cpp/string/byte/strcmp") | compares two strings (function) | | [strncmp](strncmp "cpp/string/byte/strncmp") | compares a certain number of characters from two strings (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/memcmp "c/string/byte/memcmp") for `memcmp` | cpp std::strtoimax, std::strtoumax std::strtoimax, std::strtoumax ============================== | Defined in header `[<cinttypes>](../../header/cinttypes "cpp/header/cinttypes")` | | | | --- | --- | --- | | ``` std::intmax_t strtoimax( const char* nptr, char** endptr, int base ); ``` | | (since C++11) | | ``` std::uintmax_t strtoumax( const char* nptr, char** endptr, int base ); ``` | | (since C++11) | Interprets an integer value in a byte string pointed to by `nptr`. Discards any whitespace characters (as identified by calling [`std::isspace`](isspace "cpp/string/byte/isspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) integer number representation and converts them to an integer value. The valid 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. The functions sets the pointer pointed to by `endptr` to point to the character past the last character interpreted. If `endptr` is a null pointer, it is ignored. If the `nptr` is empty or does not have the expected form, no conversion is performed, and (if `enptr` is not a null pointer) the value of `nptr` is stored in the object pointed to by `endptr`. ### Parameters | | | | | --- | --- | --- | | nptr | - | pointer to the null-terminated byte string to be interpreted | | endptr | - | pointer to a pointer to character. | | base | - | *base* of the interpreted integer value | ### Return value * If successful, an integer value corresponding to the contents of `str` is returned. * If the converted value falls out of range of corresponding return type, a range error occurs (setting `[errno](../../error/errno "cpp/error/errno")` to `[ERANGE](../../error/errno_macros "cpp/error/errno macros")`) and `[INTMAX\_MAX](../../types/integer "cpp/types/integer")`, `[INTMAX\_MIN](../../types/integer "cpp/types/integer")`, `[UINTMAX\_MAX](../../types/integer "cpp/types/integer")` or `​0​` is returned, as appropriate. * If no conversion can be performed, `​0​` is returned. ### Example ``` #include <iostream> #include <string> #include <cinttypes> int main() { std::string str = "helloworld"; std::intmax_t val = std::strtoimax(str.c_str(), nullptr, 36); std::cout << str << " in base 36 is " << val << " in base 10\n"; char* nptr; val = std::strtoimax(str.c_str(), &nptr, 30); if(nptr != &str[0] + str.size()) std::cout << str << " in base 30 is invalid." << " The first invalid digit is '" << *nptr << "'\n"; } ``` Output: ``` helloworld in base 36 is 1767707668033969 in base 10 helloworld in base 30 is invalid. The first invalid digit is 'w' ``` ### See also | | | | --- | --- | | [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) | | [strtolstrtoll](strtol "cpp/string/byte/strtol") (C++11) | converts a byte string to an integer value (function) | | [strtoulstrtoull](strtoul "cpp/string/byte/strtoul") (C++11) | converts a byte string to an unsigned integer value (function) | | [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) | | [strtofstrtodstrtold](strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [atoiatolatoll](atoi "cpp/string/byte/atoi") (C++11) | converts a byte string to an integer value (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strtoimax "c/string/byte/strtoimax") for `strtoimax, strtoumax` | cpp std::strtoul, std::strtoull std::strtoul, std::strtoull =========================== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` unsigned long strtoul( const char *str, char **str_end, int base ); ``` | | | | ``` unsigned long long strtoull( const char *str, char **str_end, int base ); ``` | | (since C++11) | Interprets an unsigned integer value in a byte string pointed to by `str`. Discards any whitespace characters (as identified by calling [`std::isspace`](isspace "cpp/string/byte/isspace")) 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 character past the last character interpreted. If `str_end` is a null pointer, it is ignored. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be interpreted | | str\_end | - | pointer to a pointer to 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 <cstdlib> int main() { const char* p = "10 200000000000000000000000000000 30 -40"; char *end; std::cout << "Parsing '" << p << "':\n"; for (unsigned long i = std::strtoul(p, &end, 10); p != end; i = std::strtoul(p, &end, 10)) { std::cout << "'" << std::string(p, end-p) << "' -> "; p = end; if (errno == ERANGE){ std::cout << "range error, got "; errno = 0; } std::cout << i << '\n'; } } ``` Possible output: ``` Parsing '10 200000000000000000000000000000 30 -40': '10' -> 10 ' 200000000000000000000000000000' -> range error, got 18446744073709551615 ' 30' -> 30 ' -40' -> 18446744073709551576 ``` ### See also | | | | --- | --- | | [stoulstoull](../basic_string/stoul "cpp/string/basic string/stoul") (C++11)(C++11) | converts a string to an unsigned integer (function) | | [strtolstrtoll](strtol "cpp/string/byte/strtol") (C++11) | converts a byte string to an integer value (function) | | [strtoimaxstrtoumax](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) | | [wcstoulwcstoull](../wide/wcstoul "cpp/string/wide/wcstoul") | converts a wide string to an unsigned integer value (function) | | [strtofstrtodstrtold](strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [atoiatolatoll](atoi "cpp/string/byte/atoi") (C++11) | converts a byte string to an integer value (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strtoul "c/string/byte/strtoul") for `strtoul, strtoull` |
programming_docs
cpp std::isspace std::isspace ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isspace( int ch ); ``` | | | Checks if the given character is whitespace character as classified by the currently installed C locale. In the default locale, the whitespace characters are the following: * space (`0x20`, `' '`) * form feed (`0x0c`, `'\f'`) * line feed (`0x0a`, `'\n'`) * carriage return (`0x0d`, `'\r'`) * horizontal tab (`0x09`, `'\t'`) * vertical tab (`0x0b`, `'\v'`) The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is a whitespace character, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isspace` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isspace(char ch) { return std::isspace(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_spaces(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isspace) // wrong // [](int c){ return std::isspace(c); } // wrong // [](char c){ return std::isspace(c); } // wrong [](unsigned char c){ return std::isspace(c); } // correct ); } ``` ### See also | | | | --- | --- | | [isspace(std::locale)](../../locale/isspace "cpp/locale/isspace") | checks if a character is classified as whitespace by a locale (function template) | | [iswspace](../wide/iswspace "cpp/string/wide/iswspace") | checks if a wide character is a space character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isspace "c/string/byte/isspace") for `isspace` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | **`isspace`** [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::strcpy std::strcpy =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` char* strcpy( char* dest, const char* src ); ``` | | | Copies the character string pointed to by `src`, including the null terminator, to the character array whose first element is pointed to by `dest`. The behavior is undefined if the `dest` array is not large enough. The behavior is undefined if the strings overlap. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the character array to write to | | src | - | pointer to the null-terminated byte string to copy from | ### Return value `dest`. ### Example ``` #include <iostream> #include <cstring> #include <memory> int main() { const char* src = "Take the test."; // src[0] = 'M'; // can't modify string literal auto dst = std::make_unique<char[]>(std::strlen(src)+1); // +1 for the null terminator std::strcpy(dst.get(), src); dst[0] = 'M'; std::cout << src << '\n' << dst.get() << '\n'; } ``` Output: ``` Take the test. Make the test. ``` ### See also | | | | --- | --- | | [strncpy](strncpy "cpp/string/byte/strncpy") | copies a certain amount of characters from one string to another (function) | | [memcpy](memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strcpy "c/string/byte/strcpy") for `strcpy` | cpp std::isupper std::isupper ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isupper( int ch ); ``` | | | Checks if the given character is an uppercase character as classified by the currently installed C locale. In the default "C" locale, `isupper` returns a nonzero value only for the uppercase letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`). If `isupper` returns a nonzero value, it is guaranteed that `iscntrl`, `isdigit`, `ispunct`, and `isspace` return zero for the same character in the same C locale. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is an uppercase letter, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isupper` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isupper(char ch) { return std::isupper(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_uppers(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isupper) // wrong // [](int c){ return std::isupper(c); } // wrong // [](char c){ return std::isupper(c); } // wrong [](unsigned char c){ return std::isupper(c); } // correct ); } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xc6'; // letter Æ in ISO-8859-1 std::cout << "isupper(\'\\xc6\', default C locale) returned " << std::boolalpha << (bool)std::isupper(c) << '\n'; std::setlocale(LC_ALL, "en_GB.iso88591"); std::cout << "isupper(\'\\xc6\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::isupper(c) << '\n'; } ``` Output: ``` isupper('\xc6', default C locale) returned false isupper('\xc6', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [isupper(std::locale)](../../locale/isupper "cpp/locale/isupper") | checks if a character is classified as uppercase by a locale (function template) | | [iswupper](../wide/iswupper "cpp/string/wide/iswupper") | checks if a wide character is an uppercase character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isupper "c/string/byte/isupper") for `isupper` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | **`isupper`** [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::strerror std::strerror ============= | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` char* strerror( int errnum ); ``` | | | Returns a pointer to the textual description of the system error code `errnum`, identical to the description that would be printed by `[std::perror()](../../io/c/perror "cpp/io/c/perror")`. `errnum` is usually acquired from the `errno` variable, however the function accepts any value of type `int`. The contents of the string are locale-specific. The returned string must not be modified by the program, but may be overwritten by a subsequent call to the `strerror` function. `strerror` is not required to be thread-safe. Implementations may be returning different pointers to static read-only string literals or may be returning the same pointer over and over, pointing at a static buffer in which strerror places the string. ### Parameters | | | | | --- | --- | --- | | errnum | - | integral value referring to a error code | ### Return value Pointer to a null-terminated byte string corresponding to the `[errno](../../error/errno "cpp/error/errno")` error code `errnum`. ### Notes [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strerror.html) allows subsequent calls to `strerror` to invalidate the pointer value returned by an earlier call. It also specifies that it is the [`LC_MESSAGES`](../../locale/lc_categories "cpp/locale/LC categories") locale facet that controls the contents of these messages. POSIX has a thread-safe version called `strerror_r` defined. Glibc [defines an incompatible version](http://www.club.cc.cmu.edu/~cmccabe/blog_strerror.html). ### Example ``` #include <iostream> #include <cmath> #include <cerrno> #include <cstring> #include <clocale> int main() { double not_a_number = std::log(-1.0); std::cout << not_a_number << '\n'; if (errno == EDOM) { std::cout << "log(-1) failed: " << std::strerror(errno) << '\n'; std::setlocale(LC_MESSAGES, "de_DE.utf8"); std::cout << "Or, in German, " << std::strerror(errno) << '\n'; } } ``` Possible output: ``` nan log(-1) failed: Numerical argument out of domain Or, in German, Das numerische Argument ist ausserhalb des Definitionsbereiches ``` ### See also | | | | --- | --- | | [perror](../../io/c/perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](../../io/c/std_streams "cpp/io/c/std streams")` (function) | | [E2BIG, EACCES, ..., EXDEV](../../error/errno_macros "cpp/error/errno macros") | macros for standard POSIX-compatible error conditions (macro constant) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strerror "c/string/byte/strerror") for `strerror` | cpp std::ispunct std::ispunct ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int ispunct( int ch ); ``` | | | Checks if the given character is a punctuation character as classified by the current C locale. The default C locale classifies the characters `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` as punctuation. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is a punctuation character, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::ispunct` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_ispunct(char ch) { return std::ispunct(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_puncts(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::ispunct) // wrong // [](int c){ return std::ispunct(c); } // wrong // [](char c){ return std::ispunct(c); } // wrong [](unsigned char c){ return std::ispunct(c); } // correct ); } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xd7'; // the character × (multiplication sign) in ISO-8859-1 std::cout << "ispunct(\'\\xd7\', default C locale) returned " << std::boolalpha << (bool)std::ispunct(c) << '\n'; std::setlocale(LC_ALL, "en_GB.iso88591"); std::cout << "ispunct(\'\\xd7\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::ispunct(c) << '\n'; } ``` Output: ``` ispunct('\xd7', default C locale) returned false ispunct('\xd7', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [ispunct(std::locale)](../../locale/ispunct "cpp/locale/ispunct") | checks if a character is classified as punctuation by a locale (function template) | | [iswpunct](../wide/iswpunct "cpp/string/wide/iswpunct") | checks if a wide character is a punctuation character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/ispunct "c/string/byte/ispunct") for `ispunct` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | **`ispunct`** [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** |
programming_docs
cpp std::iscntrl std::iscntrl ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int iscntrl( int ch ); ``` | | | Checks if the given character is a control character as classified by the currently installed C locale. In the default, "C" locale, the control characters are the characters with the codes `0x00-0x1F` and `0x7F`. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is a control character, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::iscntrl` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_iscntrl(char ch) { return std::iscntrl(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_cntrls(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::iscntrl) // wrong // [](int c){ return std::iscntrl(c); } // wrong // [](char c){ return std::iscntrl(c); } // wrong [](unsigned char c){ return std::iscntrl(c); } // correct ); } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\x94'; // the control code CCH in ISO-8859-1 std::cout << "iscntrl(\'\\x94\', default C locale) returned " << std::boolalpha << (bool)std::iscntrl(c) << '\n'; std::setlocale(LC_ALL, "en_GB.iso88591"); std::cout << "iscntrl(\'\\x94\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::iscntrl(c) << '\n'; } ``` Output: ``` iscntrl('\x94', default C locale) returned false iscntrl('\x94', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [iscntrl(std::locale)](../../locale/iscntrl "cpp/locale/iscntrl") | checks if a character is classified as a control character by a locale (function template) | | [iswcntrl](../wide/iswcntrl "cpp/string/wide/iswcntrl") | checks if a wide character is a control character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/iscntrl "c/string/byte/iscntrl") for `iscntrl` | | ASCII values | characters | **`iscntrl`** [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::strcoll std::strcoll ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` int strcoll( const char* lhs, const char* rhs ); ``` | | | Compares two null-terminated byte strings according to the current locale as defined by the `[LC\_COLLATE](../../locale/lc_categories "cpp/locale/LC categories")` category. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pointers to the null-terminated byte 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 <cstring> #include <clocale> int main() { std::setlocale(LC_COLLATE, "cs_CZ.iso88592"); const char* s1 = "hrnec"; const char* s2 = "chrt"; std::cout << "In the Czech locale: "; if(std::strcoll(s1, s2) < 0) std::cout << s1 << " before " << s2 << '\n'; else std::cout << s2 << " before " << s1 << '\n'; std::cout << "In lexicographical comparison: "; if(std::strcmp(s1, s2) < 0) std::cout << s1 << " before " << s2 << '\n'; else std::cout << s2 << " before " << s1 << '\n'; } ``` Output: ``` In the Czech locale: hrnec before chrt In lexicographical comparison: chrt before hrnec ``` ### See also | | | | --- | --- | | [wcscoll](../wide/wcscoll "cpp/string/wide/wcscoll") | compares two wide 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>`) | | [strxfrm](strxfrm "cpp/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strcoll "c/string/byte/strcoll") for `strcoll` | cpp std::isdigit std::isdigit ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isdigit( int ch ); ``` | | | Checks if the given character is one of the 10 decimal digits: `0123456789`. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is a numeric character, zero otherwise. ### Notes `isdigit` and `isxdigit` are the only standard narrow character classification functions that are not affected by the currently installed C locale. although some implementations (e.g. Microsoft in 1252 codepage) may classify additional single-byte characters as digits. Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isdigit` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isdigit(char ch) { return std::isdigit(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_digits(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isdigit) // wrong // [](int c){ return std::isdigit(c); } // wrong // [](char c){ return std::isdigit(c); } // wrong [](unsigned char c){ return std::isdigit(c); } // correct ); } ``` ### See also | | | | --- | --- | | [isdigit(std::locale)](../../locale/isdigit "cpp/locale/isdigit") | checks if a character is classified as a digit by a locale (function template) | | [iswdigit](../wide/iswdigit "cpp/string/wide/iswdigit") | checks if a wide character is a digit (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isdigit "c/string/byte/isdigit") for `isdigit` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | **`isdigit`** [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::strpbrk std::strpbrk ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` const char* strpbrk( const char* dest, const char* breakset ); ``` | | | | ``` char* strpbrk( char* dest, const char* breakset ); ``` | | | Scans the null-terminated byte string pointed to by `dest` for any character from the null-terminated byte string pointed to by `breakset`, and returns a pointer to that character. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated byte string to be analyzed | | breakset | - | pointer to the null-terminated byte string that contains the characters to search for | ### Return value Pointer to the first character in `dest`, that is also in `breakset`, or null pointer if no such character exists. ### Notes The name stands for "string pointer break", because it returns a pointer to the first of the separator ("break") characters. ### Example ``` #include <iostream> #include <cstring> #include <iomanip> int main() { const char* str = "hello world, friend of mine!"; const char* sep = " ,!"; unsigned int cnt = 0; do { str = std::strpbrk(str, sep); // find separator std::cout << std::quoted(str) << '\n'; if(str) str += std::strspn(str, sep); // skip separator ++cnt; // increment word count } while(str && *str); std::cout << "There are " << cnt << " words\n"; } ``` Output: ``` " world, friend of mine!" ", friend of mine!" " of mine!" " mine!" "!" There are 5 words ``` ### See also | | | | --- | --- | | [strcspn](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) | | [strtok](strtok "cpp/string/byte/strtok") | finds the next token in a byte string (function) | | [strchr](strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (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) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strpbrk "c/string/byte/strpbrk") for `strpbrk` | cpp std::strncmp std::strncmp ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` int strncmp( const char *lhs, const char *rhs, std::size_t count ); ``` | | | Compares at most `count` characters of two possibly null-terminated arrays. The comparison is done lexicographically. Characters following the null character are not compared. The sign of the result is the sign of the difference between the values of the first pair of characters (both interpreted as `unsigned char`) that differ in the arrays being compared. The behavior is undefined when access occurs past the end of either array `lhs` or `rhs`. The behavior is undefined when either `lhs` or `rhs` is the null pointer. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pointers to the possibly null-terminated arrays to compare | | count | - | maximum number of characters to compare | ### Return value Negative value if `lhs` appears before `rhs` in lexicographical order. Zero if `lhs` and `rhs` compare equal, or if count is zero. Positive value if `lhs` appears after `rhs` in lexicographical order. ### Notes This function is not locale-sensitive, unlike `[std::strcoll](strcoll "cpp/string/byte/strcoll")` and `[std::strxfrm](strxfrm "cpp/string/byte/strxfrm")`. ### Example ``` #include <cstring> #include <iostream> void demo(const char* lhs, const char* rhs, int sz) { int rc = std::strncmp(lhs, rhs, sz); if(rc == 0) std::cout << "First " << sz << " chars of [" << lhs << "] equal [" << rhs << "]\n"; else if(rc < 0) std::cout << "First " << sz << " chars of [" << lhs << "] precede [" << rhs << "]\n"; else if(rc > 0) std::cout << "First " << sz << " chars of [" << lhs << "] follow [" << rhs << "]\n"; } int main() { demo("Hello, world!", "Hello, everybody!", 13); demo("Hello, everybody!", "Hello, world!", 13); demo("Hello, everybody!", "Hello, world!", 7); demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5); } ``` Output: ``` First 13 chars of [Hello, world!] follow [Hello, everybody!] First 13 chars of [Hello, everybody!] precede [Hello, world!] First 7 chars of [Hello, everybody!] equal [Hello, world!] First 5 chars of [body!] equal [body!] ``` ### See also | | | | --- | --- | | [strcmp](strcmp "cpp/string/byte/strcmp") | compares two strings (function) | | [wcsncmp](../wide/wcsncmp "cpp/string/wide/wcsncmp") | compares a certain amount of characters from two wide strings (function) | | [memcmp](memcmp "cpp/string/byte/memcmp") | compares two buffers (function) | | [strcoll](strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strncmp "c/string/byte/strncmp") for `strncmp` |
programming_docs
cpp std::strxfrm std::strxfrm ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` std::size_t strxfrm( char* dest, const char* src, std::size_t count ); ``` | | | Transforms the null-terminated byte string pointed to by `src` into the implementation-defined form such that comparing two transformed strings with `[std::strcmp](strcmp "cpp/string/byte/strcmp")` gives the same result as comparing the original strings with `[std::strcoll](strcoll "cpp/string/byte/strcoll")`, 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. The behavior is undefined if the `dest` array is not large enough. The behavior is undefined if `dest` and `src` overlap. 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::strxfrm(nullptr, src, 0)`. This function is used when making multiple locale-dependent comparisons using the same string or set of strings, because it is more efficient to use `std::strxfrm` to transform all the strings just once, and subsequently compare the transformed strings with `[std::strcmp](strcmp "cpp/string/byte/strcmp")`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the first element of the array where the transformed string will be written | | src | - | pointer to the first character of a null-terminated byte string to transform | | count | - | maximum number of characters to be written | ### Return value The length of the transformed string, not including the terminating null-character. ### Example ``` #include <iostream> #include <iomanip> #include <cstring> #include <string> #include <cassert> int main() { char* loc = std::setlocale(LC_COLLATE, "cs_CZ.iso88592"); assert(loc); std::string in1 = "hrnec"; std::string out1(1+std::strxfrm(nullptr, in1.c_str(), 0), ' '); std::string in2 = "chrt"; std::string out2(1+std::strxfrm(nullptr, in2.c_str(), 0), ' '); std::strxfrm(&out1[0], in1.c_str(), out1.size()); std::strxfrm(&out2[0], in2.c_str(), out2.size()); std::cout << "In the Czech locale: "; if(out1 < out2) std::cout << in1 << " before " << in2 << '\n'; else std::cout << in2 << " before " << in1 << '\n'; std::cout << "In lexicographical comparison: "; if(in1 < in2) std::cout << in1 << " before " << in2 << '\n'; else std::cout << in2 << " before " << in1 << '\n'; } ``` Possible output: ``` In the Czech locale: hrnec before chrt In lexicographical comparison: chrt before hrnec ``` ### See also | | | | --- | --- | | [wcsxfrm](../wide/wcsxfrm "cpp/string/wide/wcsxfrm") | transform a wide string so that wcscmp would produce the same result as wcscoll (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>`) | | [strcoll](strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strxfrm "c/string/byte/strxfrm") for `strxfrm` | cpp std::atof std::atof ========= | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` double atof( const char *str ); ``` | | | Interprets a floating point value in a byte string pointed to by `str`. Function discards any whitespace characters (as determined by `std::isspace()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following: * decimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10) | | | | --- | --- | | * hexadecimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + `0x` or `0X` + nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2) * infinity expression. It consists of the following parts: + (optional) plus or minus sign + `INF` or `INFINITY` ignoring case * not-a-number expression. It consists of the following parts: + (optional) plus or minus sign + `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value. | (since C++11) | * any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "cpp/locale/setlocale") ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be interpreted | ### Return value `double` value corresponding to the contents of `str` on success. If the converted value falls out of range of the return type, the return value is undefined. If no conversion can be performed, `0.0` is returned. ### Example ``` #include <cstdlib> #include <iostream> int main() { std::cout << std::atof("0.0000000123") << '\n' << std::atof("0.012") << '\n' << std::atof("15e16") << '\n' << std::atof("-0x1afp-2") << '\n' << std::atof("inF") << '\n' << std::atof("Nan") << '\n' << std::atof("invalid") << '\n'; } ``` Output: ``` 1.23e-08 0.012 1.5e+17 -107.75 inf nan 0 ``` ### See also | | | | --- | --- | | [stofstodstold](../basic_string/stof "cpp/string/basic string/stof") (C++11)(C++11)(C++11) | converts a string to a floating point value (function) | | [strtofstrtodstrtold](strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [atoiatolatoll](atoi "cpp/string/byte/atoi") (C++11) | converts a byte string to an integer value (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/atof "c/string/byte/atof") for `atof` | cpp std::memchr std::memchr =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` const void* memchr( const void* ptr, int ch, std::size_t count ); ``` | | | | ``` void* memchr( void* ptr, int ch, std::size_t count ); ``` | | | Converts `ch` to `unsigned char` and locates the first occurrence of that value in the initial `count` bytes (each interpreted as `unsigned char`) of the object pointed to by `ptr`. | | | | --- | --- | | This function behaves as if it reads the bytes sequentially and stops as soon as a matching bytes is found: if the array pointed to by `ptr` is smaller than `count`, but the match is found within the array, the behavior is well-defined. | (since C++17) | ### Parameters | | | | | --- | --- | --- | | ptr | - | pointer to the object to be examined | | ch | - | byte to search for | | count | - | max number of bytes to examine | ### Return value Pointer to the location of the byte, or a null pointer if no such byte is found. ### Example Search an array of characters. ``` #include <iostream> #include <cstring> int main() { char arr[] = {'a','\0','a','A','a','a','A','a'}; char *pc = (char*)std::memchr(arr,'A',sizeof arr); if (pc != nullptr) std::cout << "search character found\n"; else std::cout << "search character not found\n"; } ``` Output: ``` search character found ``` ### See also | | | | --- | --- | | [strchr](strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) | | [findfind\_iffind\_if\_not](../../algorithm/find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [C documentation](https://en.cppreference.com/w/c/string/byte/memchr "c/string/byte/memchr") for `memchr` | cpp std::strcspn std::strcspn ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` size_t strcspn( const char *dest, const char *src ); ``` | | | Returns the length of the maximum initial segment of the byte string pointed to by `dest`, that consists of only the characters *not* found in byte string pointed to by `src`. The function name stands for "complementary span" ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated byte string to be analyzed | | src | - | pointer to the null-terminated byte string that contains the characters to search for | ### Return value The length of the maximum initial segment that contains only characters not found in the byte string pointed to by `src`. ### Example ``` #include <string> #include <cstring> #include <iostream> const char* invalid = "*$#"; int main() { std::string s = "abcde312$#@"; size_t valid_len = std::strcspn(s.c_str(), invalid); if(valid_len != s.size()) std::cout << "'" << s << "' contains invalid chars starting at position " << valid_len << '\n'; } ``` Output: ``` 'abcde312$#@' contains invalid chars starting at position 8 ``` ### See also | | | | --- | --- | | [strspn](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) | | [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) | | [strpbrk](strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) | | [find\_first\_of](../basic_string/find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strcspn "c/string/byte/strcspn") for `strcspn` | cpp std::isalpha std::isalpha ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isalpha( int ch ); ``` | | | Checks if the given character is an alphabetic character as classified by the currently installed C locale. In the default locale, the following characters are alphabetic: * uppercase letters `ABCDEFGHIJKLMNOPQRSTUVWXYZ` * lowercase letters `abcdefghijklmnopqrstuvwxyz` In locales other than `"C"`, an alphabetic character is a character for which `std::isupper()` or `std::islower()` returns non-zero or any other character considered alphabetic by the locale. In any case, `std::iscntrl()`, `std::isdigit()`, `std::ispunct()` and `std::isspace()` will return zero for this character. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is an alphabetic character, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isalpha` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isalpha(char ch) { return std::isalpha(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_alphas(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isalpha) // wrong // [](int c){ return std::isalpha(c); } // wrong // [](char c){ return std::isalpha(c); } // wrong [](unsigned char c){ return std::isalpha(c); } // correct ); } ``` ### Example Demonstrates the use of isalpha() with different locales (OS-specific). ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xdf'; // German letter ß in ISO-8859-1 std::cout << "isalpha(\'\\xdf\', default C locale) returned " << std::boolalpha << (bool)std::isalpha(c) << '\n'; std::setlocale(LC_ALL, "de_DE.iso88591"); std::cout << "isalpha(\'\\xdf\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::isalpha(c) << '\n'; } ``` Output: ``` isalpha('\xdf', default C locale) returned false isalpha('\xdf', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [isalpha(std::locale)](../../locale/isalpha "cpp/locale/isalpha") | checks if a character is classified as alphabetic by a locale (function template) | | [iswalpha](../wide/iswalpha "cpp/string/wide/iswalpha") | checks if a wide character is alphabetic (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isalpha "c/string/byte/isalpha") for `isalpha` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | **`isalpha`** [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::isgraph std::isgraph ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isgraph( int ch ); ``` | | | Checks if the given character is graphic (has a graphical representation) as classified by the currently installed C locale. In the default C locale, the following characters are graphic: * digits (`0123456789`) * uppercase letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`) * lowercase letters (`abcdefghijklmnopqrstuvwxyz`) * punctuation characters (`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`) The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character has a graphical representation character, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isgraph` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isgraph(char ch) { return std::isgraph(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_graphs(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isgraph) // wrong // [](int c){ return std::isgraph(c); } // wrong // [](char c){ return std::isgraph(c); } // wrong [](unsigned char c){ return std::isgraph(c); } // correct ); } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xb6'; // the character ¶ in ISO-8859-1 std::cout << "isgraph(\'\\xb6\', default C locale) returned " << std::boolalpha << (bool)std::isgraph(c) << '\n'; std::setlocale(LC_ALL, "en_GB.iso88591"); std::cout << "isgraph(\'\\xb6\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::isgraph(c) << '\n'; } ``` Output: ``` isgraph('\xb6', default C locale) returned false isgraph('\xb6', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [isgraph(std::locale)](../../locale/isgraph "cpp/locale/isgraph") | checks if a character is classfied as graphical by a locale (function template) | | [iswgraph](../wide/iswgraph "cpp/string/wide/iswgraph") | checks if a wide character is a graphical character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isgraph "c/string/byte/isgraph") for `isgraph` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | **`isgraph`** [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** |
programming_docs
cpp std::strspn std::strspn =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` size_t strspn( const char* dest, const char* src ); ``` | | | Returns the length of the maximum initial segment (span) of the byte string pointed to by `dest`, that consists of only the characters found in byte string pointed to by `src`. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated byte string to be analyzed | | src | - | pointer to the null-terminated byte string that contains the characters to search for | ### Return value The length of the maximum initial segment that contains only characters from byte string pointed to by `src`. ### Example ``` #include <cstring> #include <string> #include <iostream> const char *low_alpha = "qwertyuiopasdfghjklzxcvbnm"; int main() { std::string s = "abcde312$#@"; std::size_t spnsz = std::strspn(s.c_str(), low_alpha); std::cout << "After skipping initial lowercase letters from '" << s << "'\nThe remainder is '" << s.substr(spnsz) << "'\n"; } ``` Output: ``` After skipping initial lowercase letters from 'abcde312$#@' The remainder is '312$#@' ``` ### See also | | | | --- | --- | | [strcspn](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) | | [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) | | [strpbrk](strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strspn "c/string/byte/strspn") for `strspn` | cpp std::atoi, std::atol, std::atoll std::atoi, std::atol, std::atoll ================================ | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` int atoi( const char *str ); ``` | | | | ``` long atol( const char *str ); ``` | | | | ``` long long atoll( const char *str ); ``` | | (since C++11) | Interprets an integer value in a byte string pointed to by `str`. Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts: * (optional) plus or minus sign * numeric digits ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be interpreted | ### Return value Integer value corresponding to the contents of `str` on success. If no conversion can be performed, `​0​` is returned. If the value of the result cannot be represented, i.e. the converted value falls out of range of the corresponding return type, behavior is undefined. ### Example ``` #include <cstdlib> #include <iostream> int main() { const auto data = { "42", "3.14159", "31337 with words", "words and 2", "-012345", "10000000000" }; for (const char* s : data) { const int i {std::atoi(s)}; std::cout << "std::atoi('" << s << "') is " << i << '\n'; if (const long long ll {std::atoll(s)}; i != ll) { std::cout << "std::atoll('" << s << "') is " << ll << '\n'; } } } ``` Possible output: ``` std::atoi('42') is 42 std::atoi('3.14159') is 3 std::atoi('31337 with words') is 31337 std::atoi('words and 2') is 0 std::atoi('-012345') is -12345 std::atoi('10000000000') is 1410065408 std::atoll('10000000000') is 10000000000 ``` ### See also | | | | --- | --- | | [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) | | [strtolstrtoll](strtol "cpp/string/byte/strtol") (C++11) | converts a byte string to an integer value (function) | | [strtoulstrtoull](strtoul "cpp/string/byte/strtoul") (C++11) | converts a byte string to an unsigned integer value (function) | | [strtoimaxstrtoumax](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) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/atoi "c/string/byte/atoi") for `atoi, atol, atoll` | cpp std::islower std::islower ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int islower( int ch ); ``` | | | Checks if the given character is classified as a lowercase character according to the current C locale. In the default "C" locale, `islower` returns a nonzero value only for the lowercase letters (`abcdefghijklmnopqrstuvwxyz`). If `islower` returns a nonzero value, it is guaranteed that `iscntrl`, `isdigit`, `ispunct`, and `isspace` return zero for the same character in the same C locale. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is a lowercase letter, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::islower` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_islower(char ch) { return std::islower(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_lowers(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::islower) // wrong // [](int c){ return std::islower(c); } // wrong // [](char c){ return std::islower(c); } // wrong [](unsigned char c){ return std::islower(c); } // correct ); } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xe5'; // letter å in ISO-8859-1 std::cout << "islower(\'\\xe5\', default C locale) returned " << std::boolalpha << (bool)std::islower(c) << '\n'; std::setlocale(LC_ALL, "en_GB.iso88591"); std::cout << "islower(\'\\xe5\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::islower(c) << '\n'; } ``` Output: ``` islower('\xe5', default C locale) returned false islower('\xe5', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [islower(std::locale)](../../locale/islower "cpp/locale/islower") | checks if a character is classified as lowercase by a locale (function template) | | [iswlower](../wide/iswlower "cpp/string/wide/iswlower") | checks if a wide character is lowercase (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/islower "c/string/byte/islower") for `islower` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | **`islower`** [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::isblank std::isblank ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isblank( int ch ); ``` | | (since C++11) | Checks if the given character is a blank character as classified by the currently installed C locale. Blank characters are whitespace characters used to separate words within a sentence. In the default C locale, only space (`0x20`) and horizontal tab (`0x09`) are classified as blank characters. The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is a blank character, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isblank` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isblank(char ch) { return std::isblank(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_blanks(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isblank) // wrong // [](int c){ return std::isblank(c); } // wrong // [](char c){ return std::isblank(c); } // wrong [](unsigned char c){ return std::isblank(c); } // correct ); } ``` ### See also | | | | --- | --- | | [isblank(std::locale)](../../locale/isblank "cpp/locale/isblank") (C++11) | checks if a character is classified as a blank character by a locale (function template) | | [iswblank](../wide/iswblank "cpp/string/wide/iswblank") (C++11) | checks if a wide character is a blank character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isblank "c/string/byte/isblank") for `isblank` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | **`isblank`** [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::memmove std::memmove ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` void* memmove( void* dest, const void* src, std::size_t count ); ``` | | | Copies `count` characters from the object pointed to by `src` to the object pointed to by `dest`. Both objects are reinterpreted as arrays of `unsigned char`. The objects may overlap: copying takes place as if the characters were copied to a temporary character array and then the characters were copied from the array to `dest`. If either `dest` or `src` is an [invalid or null pointer](../../language/pointer#Pointers "cpp/language/pointer"), the behavior is undefined, even if `count` is zero. If the objects are [potentially-overlapping](../../language/object#Subobjects "cpp/language/object") or not [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), the behavior of `memmove` is not specified and [may be undefined](http://stackoverflow.com/questions/29777492). ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the memory location to copy to | | src | - | pointer to the memory location to copy from | | count | - | number of bytes to copy | ### Return value `dest`. ### Notes `std::memmove` may be used to [implicitly create](../../language/object#Object_creation "cpp/language/object") objects in the destination buffer. Despite being specified "as if" a temporary buffer is used, actual implementations of this function do not incur the overhead of double copying or extra memory. For small `count`, it may load up and write out registers; for larger blocks, a common approach (glibc and bsd libc) is to copy bytes forwards from the beginning of the buffer if the destination starts before the source, and backwards from the end otherwise, with a fall back to `[std::memcpy](memcpy "cpp/string/byte/memcpy")` when there is no overlap at all. Where [strict aliasing](../../language/object#Strict_aliasing "cpp/language/object") prohibits examining the same memory as values of two different types, `std::memmove` may be used to convert the values. ### Example ``` #include <iostream> #include <cstring> int main() { char str[] = "1234567890"; std::cout << str << '\n'; std::memmove(str + 4, str + 3, 3); // copies from [4, 5, 6] to [5, 6, 7] std::cout << str << '\n'; } ``` Output: ``` 1234567890 1234456890 ``` ### See also | | | | --- | --- | | [memcpy](memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) | | [memset](memset "cpp/string/byte/memset") | fills a buffer with a character (function) | | [wmemmove](../wide/wmemmove "cpp/string/wide/wmemmove") | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) | | [copycopy\_if](../../algorithm/copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [copy\_backward](../../algorithm/copy_backward "cpp/algorithm/copy backward") | copies a range of elements in backwards order (function template) | | [is\_trivially\_copyable](../../types/is_trivially_copyable "cpp/types/is trivially copyable") (C++11) | checks if a type is trivially copyable (class template) | | [C documentation](https://en.cppreference.com/w/c/string/byte/memmove "c/string/byte/memmove") for `memmove` |
programming_docs
cpp std::strcmp std::strcmp =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` int strcmp( const char *lhs, const char *rhs ); ``` | | | Compares two null-terminated byte strings lexicographically. The sign of the result is the sign of the difference between the values of the first pair of characters (both interpreted as `unsigned char`) that differ in the strings being compared. The behavior is undefined if `lhs` or `rhs` are not pointers to null-terminated strings. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | pointers to the null-terminated byte strings to compare | ### Return value Negative value if `lhs` appears before `rhs` in lexicographical order. Zero if `lhs` and `rhs` compare equal. Positive value if `lhs` appears after `rhs` in lexicographical order. ### Example ``` #include <vector> #include <cstring> #include <algorithm> #include <iostream> int main() { std::vector<const char*> cats {"Heathcliff", "Snagglepuss", "Hobbes", "Garfield"}; std::sort(cats.begin(), cats.end(), [](const char *strA, const char *strB) { return std::strcmp(strA, strB) < 0; }); for (const char *cat : cats) { std::cout << cat << '\n'; } } ``` Output: ``` Garfield Heathcliff Hobbes Snagglepuss ``` ### See also | | | | --- | --- | | [strncmp](strncmp "cpp/string/byte/strncmp") | compares a certain number of characters from two strings (function) | | [wcscmp](../wide/wcscmp "cpp/string/wide/wcscmp") | compares two wide strings (function) | | [memcmp](memcmp "cpp/string/byte/memcmp") | compares two buffers (function) | | [strcoll](strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strcmp "c/string/byte/strcmp") for `strcmp` | cpp std::strtol, std::strtoll std::strtol, std::strtoll ========================= | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` long strtol( const char *str, char **str_end, int base ); ``` | | | | ``` long long strtoll( const char *str, char **str_end, int base ); ``` | | (since C++11) | Interprets an integer value in a byte string pointed to by `str`. Discards any whitespace characters (as identified by calling [`std::isspace`](isspace "cpp/string/byte/isspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) integer number representation and converts them to an integer value. The valid 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. The function sets the pointer pointed to by `str_end` to point to the character past the last character interpreted. If `str_end` is a null pointer, it is ignored. If the `str` is empty or does not have the expected form, no conversion is performed, and (if `str_end` is not a null pointer) the value of `str` is stored in the object pointed to by `str_end`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be interpreted | | str\_end | - | pointer to a pointer to character. | | base | - | *base* of the interpreted integer value | ### Return value * If successful, an integer value corresponding to the contents of `str` is returned. * If the converted value falls out of range of corresponding return type, a range error occurs (setting `[errno](../../error/errno "cpp/error/errno")` to `[ERANGE](../../error/errno_macros "cpp/error/errno macros")`) and `[LONG\_MAX](../../types/climits "cpp/types/climits")`, `[LONG\_MIN](../../types/climits "cpp/types/climits")`, `[LLONG\_MAX](../../types/climits "cpp/types/climits")` or `[LLONG\_MIN](../../types/climits "cpp/types/climits")` is returned. * If no conversion can be performed, `​0​` is returned. ### Example ``` #include <cerrno> #include <cstdlib> #include <iomanip> #include <iostream> #include <string> int main() { const char* p = "10 200000000000000000000000000000 30 -40"; std::cout << "Parsing " << std::quoted(p) << ":\n"; for (;;) { // errno can be set to any non-zero value by a library function call // regardless of whether there was an error, so it needs to be cleared // in order to check the error set by strtol errno = 0; char* p_end; const long i = std::strtol(p, &p_end, 10); if (p == p_end) break; const bool range_error = errno == ERANGE; const std::string extracted(p, p_end - p); p = p_end; std::cout << "Extracted " << std::quoted(extracted) << ", strtol returned " << i << '.'; if (range_error) std::cout << " Range error occurred."; std::cout << '\n'; } } ``` Possible output: ``` Parsing "10 200000000000000000000000000000 30 -40": Extracted "10", strtol returned 10. Extracted " 200000000000000000000000000000", strtol returned 9223372036854775807. Range error occurred. Extracted " 30", strtol returned 30. Extracted " -40", strtol returned -40. ``` ### See also | | | | --- | --- | | [stoistolstoll](../basic_string/stol "cpp/string/basic string/stol") (C++11)(C++11)(C++11) | converts a string to a signed integer (function) | | [strtoulstrtoull](strtoul "cpp/string/byte/strtoul") (C++11) | converts a byte string to an unsigned integer value (function) | | [strtoimaxstrtoumax](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) | | [wcstolwcstoll](../wide/wcstol "cpp/string/wide/wcstol") | converts a wide string to an integer value (function) | | [strtofstrtodstrtold](strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [atoiatolatoll](atoi "cpp/string/byte/atoi") (C++11) | converts a byte string to an integer value (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strtol "c/string/byte/strtol") for `strtol, strtoll` | cpp std::memcpy std::memcpy =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` void* memcpy( void* dest, const void* src, std::size_t count ); ``` | | | Copies `count` bytes from the object pointed to by `src` to the object pointed to by `dest`. Both objects are reinterpreted as arrays of `unsigned char`. If the objects overlap, the behavior is undefined. If either `dest` or `src` is an [invalid or null pointer](../../language/pointer#Pointers "cpp/language/pointer"), the behavior is undefined, even if `count` is zero. If the objects are [potentially-overlapping](../../language/object#Subobjects "cpp/language/object") or not [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), the behavior of `memcpy` is not specified and [may be undefined](http://stackoverflow.com/questions/29777492). ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the memory location to copy to | | src | - | pointer to the memory location to copy from | | count | - | number of bytes to copy | ### Return value `dest`. ### Notes `std::memcpy` may be used to [implicitly create](../../language/object#Object_creation "cpp/language/object") objects in the destination buffer. `std::memcpy` is meant to be the fastest library routine for memory-to-memory copy. It is usually more efficient than `[std::strcpy](strcpy "cpp/string/byte/strcpy")`, which must scan the data it copies or `[std::memmove](memmove "cpp/string/byte/memmove")`, which must take precautions to handle overlapping inputs. Several C++ compilers transform suitable memory-copying loops to `std::memcpy` calls. Where [strict aliasing](../../language/object#Strict_aliasing "cpp/language/object") prohibits examining the same memory as values of two different types, `std::memcpy` may be used to convert the values. ### Example ``` #include <iostream> #include <cstdint> #include <cstring> int main() { // simple usage char source[] = "once upon a midnight dreary...", dest[4]; std::memcpy(dest, source, sizeof dest); std::cout << "dest[4] = { "; for (char c : dest) std::cout << "'" << c << "', "; std::cout << "};\n"; // reinterpreting double d = 0.1; // std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing violation std::int64_t n; std::memcpy(&n, &d, sizeof d); // OK std::cout << std::hexfloat << d << " is " << std::hex << n << " as an std::int64_t\n" << std::dec; // object creation in destination buffer struct S { int x{42}; void print() const { std::cout << "{" << x << "}\n"; } } s; alignas(S) char buf[sizeof(S)]; S* ps = new (buf) S; // placement new std::memcpy(ps, &s, sizeof s); ps->print(); } ``` Output: ``` dest[4] = { 'o', 'n', 'c', 'e', }; 0x1.999999999999ap-4 is 3fb999999999999a as an std::int64_t {42} ``` ### See also | | | | --- | --- | | [memmove](memmove "cpp/string/byte/memmove") | moves one buffer to another (function) | | [memset](memset "cpp/string/byte/memset") | fills a buffer with a character (function) | | [wmemcpy](../wide/wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) | | [copy](../basic_string/copy "cpp/string/basic string/copy") | copies characters (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [copycopy\_if](../../algorithm/copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [copy\_backward](../../algorithm/copy_backward "cpp/algorithm/copy backward") | copies a range of elements in backwards order (function template) | | [is\_trivially\_copyable](../../types/is_trivially_copyable "cpp/types/is trivially copyable") (C++11) | checks if a type is trivially copyable (class template) | | [C documentation](https://en.cppreference.com/w/c/string/byte/memcpy "c/string/byte/memcpy") for `memcpy` | cpp std::strlen std::strlen =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` std::size_t strlen( const char* str ); ``` | | | Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by `str` up to and not including the first null character. The behavior is undefined if there is no null character in the character array pointed to by `str`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be examined | ### Return value The length of the null-terminated string `str`. ### Possible implementation | | | --- | | ``` std::size_t strlen(const char* start) { // NB: no nullptr checking! const char* end = start; for( ; *end != '\0'; ++end) ; return end - start; } ``` | ### Example ``` #include <cstring> #include <iostream> int main() { const char str[] = "How many characters does this string contain?"; std::cout << "without null character: " << std::strlen(str) << '\n' << "with null character: " << sizeof str << '\n'; } ``` Output: ``` without null character: 45 with null character: 46 ``` ### See also | | | | --- | --- | | [wcslen](../wide/wcslen "cpp/string/wide/wcslen") | returns the length of a wide string (function) | | [mblen](../multibyte/mblen "cpp/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strlen "c/string/byte/strlen") for `strlen` | cpp std::isprint std::isprint ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isprint( int ch ); ``` | | | Checks if `ch` is a printable character as classified by the currently installed C locale. In the default, "C" locale, the following characters are printable: * digits (`0123456789`) * uppercase letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`) * lowercase letters (`abcdefghijklmnopqrstuvwxyz`) * punctuation characters (`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`) * space () The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character can be printed, zero otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isprint` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isprint(char ch) { return std::isprint(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_prints(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isprint) // wrong // [](int c){ return std::isprint(c); } // wrong // [](char c){ return std::isprint(c); } // wrong [](unsigned char c){ return std::isprint(c); } // correct ); } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xa0'; // the non-breaking space in ISO-8859-1 std::cout << "isprint(\'\\xa0\', default C locale) returned " << std::boolalpha << (bool)std::isprint(c) << '\n'; std::setlocale(LC_ALL, "en_GB.iso88591"); std::cout << "isprint(\'\\xa0\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::isprint(c) << '\n'; } ``` Output: ``` isprint('\xa0', default C locale) returned false isprint('\xa0', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [isprint(std::locale)](../../locale/isprint "cpp/locale/isprint") | checks if a character is classified as printable by a locale (function template) | | [iswprint](../wide/iswprint "cpp/string/wide/iswprint") | checks if a wide character is a printing character (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isprint "c/string/byte/isprint") for `isprint` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | **`isprint`** [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](isalnum "cpp/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** |
programming_docs
cpp std::strtok std::strtok =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` char* strtok( char* str, const char* delim ); ``` | | | Finds the next token in a null-terminated byte string pointed to by `str`. The separator characters are identified by null-terminated byte string pointed to by `delim`. This function is designed to be called multiple times to obtain successive tokens from the same string. * If `str` is not a null pointer, the call is treated as the first call to `strtok` for this particular string. The function searches for the first character which is *not* contained in `delim`. * If no such character was found, there are no tokens in `str` at all, and the function returns a null pointer. * If such character was found, it is the *beginning of the token*. The function then searches from that point on for the first character that *is* contained in `delim`. + If no such character was found, `str` has only one token, and the future calls to `strtok` will return a null pointer + If such character was found, it is *replaced* by the null character `'\0'` and the pointer to the following character is stored in a static location for subsequent invocations. * The function then returns the pointer to the beginning of the token * If `str` is a null pointer, the call is treated as a subsequent call to `strtok`: the function continues from where it left in previous invocation. The behavior is the same as if the previously stored pointer is passed as `str`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to tokenize | | delim | - | pointer to the null-terminated byte string identifying delimiters | ### Return value Pointer to the beginning of the next token or a `nullptr` if there are no more tokens. ### Notes This function is destructive: it writes the `'\0'` characters in the elements of the string `str`. In particular, a [string literal](../../language/string_literal "cpp/language/string literal") cannot be used as the first argument of `std::strtok`. Each call to this function modifies a static variable: is not thread safe. Unlike most other tokenizers, the delimiters in `std::strtok` can be different for each subsequent token, and can even depend on the contents of the previous tokens. ### Example ``` #include <cstring> #include <iostream> #include <iomanip> int main() { char input[] = "one + two * (three - four)!"; const char* delimiters = "! +- (*)"; char *token = std::strtok(input, delimiters); while (token) { std::cout << std::quoted(token) << ' '; token = std::strtok(nullptr, delimiters); } std::cout << "\nContents of the input string now:\n\""; for (std::size_t n = 0; n < sizeof input; ++n) { if (const char c = input[n]; c != '\0') std::cout << c; else std::cout << "\\0"; } std::cout << "\"\n"; } ``` Output: ``` "one" "two" "three" "four" Contents of the input string now: "one\0+ two\0* (three\0- four\0!\0" ``` ### See also | | | | --- | --- | | [strpbrk](strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) | | [strcspn](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) | | [strspn](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) | | [ranges::split\_viewviews::split](../../ranges/split_view "cpp/ranges/split view") (C++20) | a [`view`](../../ranges/view "cpp/ranges/view") over the subranges obtained from splitting another [`view`](../../ranges/view "cpp/ranges/view") using a delimiter (class template) (range adaptor object) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strtok "c/string/byte/strtok") for `strtok` | cpp std::tolower std::tolower ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int tolower( int ch ); ``` | | | Converts the given character to lowercase according to the character conversion rules defined by the currently installed C locale. In the default "C" locale, the following uppercase letters `ABCDEFGHIJKLMNOPQRSTUVWXYZ` are replaced with respective lowercase letters `abcdefghijklmnopqrstuvwxyz`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to be converted. If the value of `ch` is not representable as `unsigned char` and does not equal `[EOF](http://en.cppreference.com/w/cpp/io/c)`, the behavior is undefined | ### Return value Lowercase version of `ch` or unmodified `ch` if no lowercase version is listed in the current C locale. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::tolower` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` char my_tolower(char ch) { return static_cast<char>(std::tolower(static_cast<unsigned char>(ch))); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` std::string str_tolower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), // static_cast<int(*)(int)>(std::tolower) // wrong // [](int c){ return std::tolower(c); } // wrong // [](char c){ return std::tolower(c); } // wrong [](unsigned char c){ return std::tolower(c); } // correct ); return s; } ``` ### Example ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xb4'; // the character Ž in ISO-8859-15 // but ´ (acute accent) in ISO-8859-1 std::setlocale(LC_ALL, "en_US.iso88591"); std::cout << std::hex << std::showbase; std::cout << "in iso8859-1, tolower('0xb4') gives " << std::tolower(c) << '\n'; std::setlocale(LC_ALL, "en_US.iso885915"); std::cout << "in iso8859-15, tolower('0xb4') gives " << std::tolower(c) << '\n'; } ``` Output: ``` in iso8859-1, tolower('0xb4') gives 0xb4 in iso8859-15, tolower('0xb4') gives 0xb8 ``` ### See also | | | | --- | --- | | [toupper](toupper "cpp/string/byte/toupper") | converts a character to uppercase (function) | | [tolower(std::locale)](../../locale/tolower "cpp/locale/tolower") | converts a character to lowercase using the ctype facet of a locale (function template) | | [towlower](../wide/towlower "cpp/string/wide/towlower") | converts a wide character to lowercase (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/tolower "c/string/byte/tolower") for `tolower` | cpp std::strcat std::strcat =========== | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` char *strcat( char *dest, const char *src ); ``` | | | Appends a copy of the character string pointed to by `src` to the end of the character string pointed to by `dest`. The character `src[0]` replaces the null terminator at the end of `dest`. The resulting byte string is null-terminated. The behavior is undefined if the destination array is not large enough for the contents of both `src` and `dest` and the terminating null character. The behavior is undefined if the strings overlap. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the null-terminated byte string to append to | | src | - | pointer to the null-terminated byte string to copy from | ### Return value `dest`. ### Notes Because `strcat` needs to seek to the end of `dest` on each call, it is inefficient to concatenate many strings into one using `strcat`. ### Example ``` #include <cstring> #include <cstdio> int main() { char str[50] = "Hello "; char str2[50] = "World!"; std::strcat(str, str2); std::strcat(str, " Goodbye World!"); std::puts(str); } ``` Output: ``` Hello World! Goodbye World! ``` ### See also | | | | --- | --- | | [strncat](strncat "cpp/string/byte/strncat") | concatenates a certain amount of characters of two strings (function) | | [strcpy](strcpy "cpp/string/byte/strcpy") | copies one string to another (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strcat "c/string/byte/strcat") for `strcat` | cpp std::strrchr std::strrchr ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` const char* strrchr( const char* str, int ch ); ``` | | | | ``` char* strrchr( char* str, int ch ); ``` | | | Finds the last occurrence of `ch` (after conversion to `char`) in the byte string pointed to by `str`. The terminating null character is considered to be a part of the string and can be found if searching for `'\0'`. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be analyzed | | ch | - | character to search for | ### Return value Pointer to the found character in `str`, or null pointer if no such character is found. ### Example ``` #include <iostream> #include <cstring> int main() { char input[] = "/home/user/hello.c"; char* output = std::strrchr(input, '/'); if(output) std::cout << output+1 << '\n'; } ``` Output: ``` hello.c ``` ### See also | | | | --- | --- | | [strchr](strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) | | [wcsrchr](../wide/wcsrchr "cpp/string/wide/wcsrchr") | finds the last occurrence of a wide character in a wide string (function) | | [rfind](../basic_string/rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strrchr "c/string/byte/strrchr") for `strrchr` | cpp std::isalnum std::isalnum ============ | Defined in header `[<cctype>](../../header/cctype "cpp/header/cctype")` | | | | --- | --- | --- | | ``` int isalnum( int ch ); ``` | | | Checks if the given character is an alphanumeric character as classified by the current C locale. In the default locale, the following characters are alphanumeric: * digits (`0123456789`) * uppercase letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`) * lowercase letters (`abcdefghijklmnopqrstuvwxyz`) The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/cpp/io/c)`. ### Parameters | | | | | --- | --- | --- | | ch | - | character to classify | ### Return value Non-zero value if the character is an alphanumeric character, `0` otherwise. ### Notes Like all other functions from [`<cctype>`](../../header/cctype "cpp/header/cctype"), the behavior of `std::isalnum` is undefined if the argument's value is neither representable as `unsigned char` nor equal to `EOF`. To use these functions safely with plain `char`s (or `signed char`s), the argument should first be converted to `unsigned char`: ``` bool my_isalnum(char ch) { return std::isalnum(static_cast<unsigned char>(ch)); } ``` Similarly, they should not be directly used with standard algorithms when the iterator's value type is `char` or `signed char`. Instead, convert the value to `unsigned char` first: ``` int count_alnums(const std::string& s) { return std::count_if(s.begin(), s.end(), // static_cast<int(*)(int)>(std::isalnum) // wrong // [](int c){ return std::isalnum(c); } // wrong // [](char c){ return std::isalnum(c); } // wrong [](unsigned char c){ return std::isalnum(c); } // correct ); } ``` ### Example Demonstrates the use of `std::isalnum` with different locales (OS-specific). ``` #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xdf'; // German letter ß in ISO-8859-1 std::cout << "isalnum(\'\\xdf\', default C locale) returned " << std::boolalpha << (bool)std::isalnum(c) << '\n'; if(std::setlocale(LC_ALL, "de_DE.iso88591")) std::cout << "isalnum(\'\\xdf\', ISO-8859-1 locale) returned " << std::boolalpha << (bool)std::isalnum(c) << '\n'; } ``` Possible output: ``` isalnum('\xdf', default C locale) returned false isalnum('\xdf', ISO-8859-1 locale) returned true ``` ### See also | | | | --- | --- | | [isalnum(std::locale)](../../locale/isalnum "cpp/locale/isalnum") | checks if a character is classified as alphanumeric by a locale (function template) | | [iswalnum](../wide/iswalnum "cpp/string/wide/iswalnum") | checks if a wide character is alphanumeric (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/isalnum "c/string/byte/isalnum") for `isalnum` | | ASCII values | characters | [`iscntrl`](iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](isprint "cpp/string/byte/isprint") [`iswprint`](../wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](isspace "cpp/string/byte/isspace") [`iswspace`](../wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](isblank "cpp/string/byte/isblank") [`iswblank`](../wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](isgraph "cpp/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](ispunct "cpp/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "cpp/string/wide/iswpunct"). | **`isalnum`** [`iswalnum`](../wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](isalpha "cpp/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](isupper "cpp/string/byte/isupper") [`iswupper`](../wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](islower "cpp/string/byte/islower") [`iswlower`](../wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](isdigit "cpp/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](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`** | cpp std::strtof, std::strtod, std::strtold std::strtof, std::strtod, std::strtold ====================================== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` float strtof( const char* str, char** str_end ); ``` | | (since C++11) | | ``` double strtod( const char* str, char** str_end ); ``` | | | | ``` long double strtold( const char* str, char** str_end ); ``` | | (since C++11) | Interprets a floating point value in a byte string pointed to by `str`. Function discards any whitespace characters (as determined by `std::isspace()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following: * decimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10) | | | | --- | --- | | * hexadecimal floating-point expression. It consists of the following parts: + (optional) plus or minus sign + `0x` or `0X` + nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "cpp/locale/setlocale")) (defines significand) + (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2) * infinity expression. It consists of the following parts: + (optional) plus or minus sign + `INF` or `INFINITY` ignoring case * not-a-number expression. It consists of the following parts: + (optional) plus or minus sign + `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value. | (since C++11) | * any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "cpp/locale/setlocale") The functions sets the pointer pointed to by `str_end` to point to the character past the last character interpreted. If `str_end` is a null pointer, it is ignored. ### Parameters | | | | | --- | --- | --- | | str | - | pointer to the null-terminated byte string to be interpreted | | str\_end | - | pointer to a pointer to character. | ### Return value Floating point 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 `[HUGE\_VAL](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")`, `[HUGE\_VALF](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` or `[HUGE\_VALL](../../numeric/math/huge_val "cpp/numeric/math/HUGE VAL")` is returned. If no conversion can be performed, `​0​` is returned and \*str\_end is set to str. ### Example ``` #include <iostream> #include <string> #include <cerrno> #include <cstdlib> #include <clocale> int main() { const char* p = "111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz"; char* end; std::cout << "Parsing \"" << p << "\":\n"; for (double f = std::strtod(p, &end); p != end; f = std::strtod(p, &end)) { std::cout << " '" << std::string(p, end-p) << "' -> "; p = end; if (errno == ERANGE){ std::cout << "range error, got "; errno = 0; } std::cout << f << '\n'; } if (std::setlocale(LC_NUMERIC, "de_DE.utf8")) { std::cout << "With de_DE.utf8 locale:\n"; std::cout << " '123.45' -> " << std::strtod("123.45", 0) << '\n'; std::cout << " '123,45' -> " << std::strtod("123,45", 0) << '\n'; } } ``` Possible output: ``` Parsing "111.11 -2.22 0X1.BC70A3D70A3D7P+6 -Inf 1.18973e+4932zzz": '111.11' -> 111.11 ' -2.22' -> -2.22 ' 0X1.BC70A3D70A3D7P+6' -> 111.11 ' -Inf' -> -inf ' 1.18973e+4932' -> range error, got inf With de_DE.utf8 locale: '123.45' -> 123 '123,45' -> 123.45 ``` ### See also | | | | --- | --- | | [atof](atof "cpp/string/byte/atof") | converts a byte string to a floating point value (function) | | [wcstofwcstodwcstold](../wide/wcstof "cpp/string/wide/wcstof") | converts a wide string to a floating point value (function) | | [from\_chars](../../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strtof "c/string/byte/strtof") for `strtof, strtod, strtold` |
programming_docs
cpp std::strncpy std::strncpy ============ | Defined in header `[<cstring>](../../header/cstring "cpp/header/cstring")` | | | | --- | --- | --- | | ``` char *strncpy( char *dest, const char *src, std::size_t count ); ``` | | | Copies at most `count` characters of the byte string pointed to by `src` (including the terminating null character) to character array pointed to by `dest`. If `count` is reached before the entire string `src` was copied, the resulting character array is not null-terminated. If, after copying the terminating null character from `src`, `count` is not reached, additional null characters are written to `dest` until the total of `count` characters have been written. If the strings overlap, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | dest | - | pointer to the character array to copy to | | src | - | pointer to the byte string to copy from | | count | - | maximum number of characters to copy | ### Return value `dest`. ### Example ``` #include <iostream> #include <cstring> int main() { const char* src = "hi"; char dest[6] = {'a', 'b', 'c', 'd', 'e', 'f'}; std::strncpy(dest, src, 5); std::cout << "The contents of dest are: "; for (char c : dest) { if (c) { std::cout << c << ' '; } else { std::cout << "\\0" << ' '; } } std::cout << '\n'; } ``` Output: ``` The contents of dest are: h i \0 \0 \0 f ``` ### See also | | | | --- | --- | | [strcpy](strcpy "cpp/string/byte/strcpy") | copies one string to another (function) | | [memcpy](memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) | | [C documentation](https://en.cppreference.com/w/c/string/byte/strncpy "c/string/byte/strncpy") for `strncpy` | cpp std::mbsinit std::mbsinit ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int mbsinit( const std::mbstate_t* ps); ``` | | | If `ps` is not a null pointer, the `mbsinit` function determines whether the pointed-to `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")` object describes the initial conversion state. ### Notes Although a zero-initialized `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")` always represents the initial conversion state, there may be other values of `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")` that also represent the initial conversion state. ### Parameters | | | | | --- | --- | --- | | ps | - | pointer to the `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")` object to examine | ### Return value `​0​` if `ps` is not a null pointer and does not represent the initial conversion state, nonzero value otherwise. ### Example ``` #include <clocale> #include <string> #include <iostream> #include <cwchar> int main() { // allow mbrlen() to work with UTF-8 multibyte encoding std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding std::string str = "水"; // or u8"\u6c34" or "\xe6\xb0\xb4" std::mbstate_t mb = std::mbstate_t(); (void)std::mbrlen(&str[0], 1, &mb); if (!std::mbsinit(&mb)) { std::cout << "After processing the first 1 byte of " << str << " the conversion state is not initial\n"; } (void)std::mbrlen(&str[1], str.size()-1, &mb); if (std::mbsinit(&mb)) { std::cout << "After processing the remaining 2 bytes of " << str << ", the conversion state is initial conversion state\n"; } } ``` Output: ``` After processing the first 1 byte of 水 the conversion state is not initial After processing the remaining 2 bytes of 水, the conversion state is initial conversion state ``` ### See also | | | | --- | --- | | [mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t") | conversion state information necessary to iterate multibyte character strings (class) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbsinit "c/string/multibyte/mbsinit") for `mbsinit` | cpp std::btowc std::btowc ========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::wint_t btowc( int c ); ``` | | | Widens a single-byte character `c` to its wide character equivalent. Most multibyte character encodings use single-byte codes to represent the characters from the ASCII character set. This function may be used to convert such characters to `wchar_t`. ### Parameters | | | | | --- | --- | --- | | c | - | single-byte character to widen | ### Return value `WEOF` if `c` is `[EOF](../../io/c "cpp/io/c")`. Wide character representation of `c` if `(unsigned char)c` is a valid single-byte character in the initial shift state, `WEOF` otherwise. ### Example ``` #include <iostream> #include <cwchar> #include <clocale> void try_widen(char c) { std::wint_t w = std::btowc(c); if(w != WEOF) std::cout << "The single-byte character " << +(unsigned char)c << " widens to " << +w << '\n'; else std::cout << "The single-byte character " << +(unsigned char)c << " failed to widen\n"; } int main() { std::setlocale(LC_ALL, "lt_LT.iso88594"); std::cout << std::hex << std::showbase << "In Lithuanian ISO-8859-4 locale:\n"; try_widen('A'); try_widen('\xdf'); // German letter ß (U+00df) in ISO-8859-4 try_widen('\xf9'); // Lithuanian letter ų (U+0173) in ISO-8859-4 std::setlocale(LC_ALL, "lt_LT.utf8"); std::cout << "In Lithuanian UTF-8 locale:\n"; try_widen('A'); try_widen('\xdf'); try_widen('\xf9'); } ``` Output: ``` In Lithuanian ISO-8859-4 locale: The single-byte character 0x41 widens to 0x41 The single-byte character 0xdf widens to 0xdf The single-byte character 0xf9 widens to 0x173 In Lithuanian UTF-8 locale: The single-byte character 0x41 widens to 0x41 The single-byte character 0xdf failed to widen The single-byte character 0xf9 failed to widen ``` ### See also | | | | --- | --- | | [wctob](wctob "cpp/string/multibyte/wctob") | narrows a wide character to a single-byte narrow character, if possible (function) | | [do\_widen](../../locale/ctype/widen "cpp/locale/ctype/widen") [virtual] | converts a character or characters from `char` to `charT` (virtual protected member function of `std::ctype<CharT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/btowc "c/string/multibyte/btowc") for `btowc` | cpp std::mbrlen std::mbrlen =========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t mbrlen( const char* s, std::size_t n, std::mbstate_t* ps); ``` | | | Determines the size, in bytes, of the remainder of the multibyte character whose first byte is pointed to by `s`, given the current conversion state `ps`. This function is equivalent to the call `[std::mbrtowc](http://en.cppreference.com/w/cpp/string/multibyte/mbrtowc)(nullptr, s, n, ps?ps:&internal)` for some hidden object `internal` of type `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")`, except that the expression `ps` is evaluated only once. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to an element of a multibyte character string | | n | - | limit on the number of bytes in s that can be examined | | ps | - | pointer to the variable holding the conversion state | ### Return value `​0​` if the next `n` or fewer bytes complete the null character. The number of bytes (between `1` and `n`) that complete a valid multibyte character. `(size_t)-1` if encoding error occurs. `(size_t)-2` if the next `n` bytes are part of a possibly valid multibyte character, which is still incomplete after examining all `n` bytes. ### Example ``` #include <clocale> #include <string> #include <iostream> #include <cwchar> int main() { // allow mbrlen() to work with UTF-8 multibyte encoding std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding std::string str = "水"; // or u8"\u6c34" or "\xe6\xb0\xb4" std::mbstate_t mb = std::mbstate_t(); int len1 = std::mbrlen(&str[0], 1, &mb); if(len1 == -2) { std::cout << "The first 1 byte of " << str << " is an incomplete multibyte char (mbrlen returns -2)\n"; } int len2 = std::mbrlen(&str[1], str.size()-1, &mb); std::cout << "The remaining " << str.size()-1 << " bytes of " << str << " hold " << len2 << " bytes of the multibyte character\n"; std::cout << "Attempting to call mbrlen() in the middle of " << str << " while in initial shift state returns " << (int)mbrlen(&str[1], str.size(), &mb) << '\n'; } ``` Output: ``` The first 1 byte of 水 is an incomplete multibyte char (mbrlen returns -2) The remaining 2 bytes of 水 hold 2 bytes of the multibyte character Attempting to call mbrlen() in the middle of 水 while in initial shift state returns -1 ``` ### See also | | | | --- | --- | | [mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc") | converts the next multibyte character to wide character, given state (function) | | [mblen](mblen "cpp/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) | | [do\_length](../../locale/codecvt/length "cpp/locale/codecvt/length") [virtual] | calculates the length of the `ExternT` string that would be consumed by conversion into given `InternT` buffer (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbrlen "c/string/multibyte/mbrlen") for `mbrlen` | cpp std::mbrtowc std::mbrtowc ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t mbrtowc( wchar_t* pwc, const char* s, std::size_t n, std::mbstate_t* ps ); ``` | | | Converts a narrow multibyte character to a wide character. If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character in `s` is complete and valid, converts it to the corresponding wide character and stores it in `*pwc` (if `pwc` is not null). If `s` is a null pointer, the values of `n` and `pwc` are ignored and call is equivalent to `std::mbrtowc(nullptr, "", 1, ps)`. If the wide character produced is the null character, the conversion state stored in `*ps` is the initial shift state. ### Parameters | | | | | --- | --- | --- | | pwc | - | pointer to the location where the resulting wide character will be written | | s | - | pointer to the multibyte character string used as input | | n | - | limit on the number of bytes in s that can be examined | | ps | - | pointer to the conversion state used when interpreting the multibyte string | ### Return value The first of the following that applies: * `​0​` if the character converted from `s` (and stored in `pwc` if non-null) was the null character * the number of bytes `[1...n]` of the multibyte character successfully converted from `s` * `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-2)` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pwc`. * `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)` if encoding error occurs. Nothing is written to `*pwc`, the value `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` is stored in `[errno](../../error/errno "cpp/error/errno")` and the value of `*ps` is left unspecified. ### Example ``` #include <iostream> #include <clocale> #include <cstring> #include <cwchar> void print_mb(const char* ptr) { std::mbstate_t state = std::mbstate_t(); // initial state const char* end = ptr + std::strlen(ptr); int len; wchar_t wc; while((len = std::mbrtowc(&wc, ptr, end-ptr, &state)) > 0) { std::wcout << "Next " << len << " bytes are the character " << wc << '\n'; ptr += len; } } int main() { std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding const char* str = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋" // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; print_mb(str); } ``` Output: ``` Next 1 bytes are the character z Next 2 bytes are the character ß Next 3 bytes are the character 水 Next 4 bytes are the character 𝄋 ``` ### See also | | | | --- | --- | | [mbtowc](mbtowc "cpp/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) | | [wcrtomb](wcrtomb "cpp/string/multibyte/wcrtomb") | converts a wide character to its multibyte representation, given state (function) | | [do\_in](../../locale/codecvt/in "cpp/locale/codecvt/in") [virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbrtowc "c/string/multibyte/mbrtowc") for `mbrtowc` | cpp std::c16rtomb std::c16rtomb ============= | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | | | --- | --- | --- | | ``` std::size_t c16rtomb( char* s, char16_t c16, std::mbstate_t* ps ); ``` | | (since C++11) | Converts a single code point from variable-length 16-bit character representation (typically, UTF-16) to a narrow multibyte character representation. If `s` is not a null pointer and `c16` is the last 16-bit code unit in a valid variable-length encoding of a code point, the function determines the number of bytes necessary to store the multibyte character representation of that code point (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function. If `s` is a null pointer, the call is equivalent to `std::c16rtomb(buf, u'\0', ps)` for some internal buffer `buf`. If `c16` is not the final code unit in a 16-bit representation of a wide character, it does not write to the array pointed to by `s`, only `*ps` is updated. If c16 is the null wide character `u'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state. The multibyte encoding used by this function is specified by the currently active C locale. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to narrow character array where the multibyte character will be stored | | c16 | - | the 16-bit character to convert | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value On success, returns the number of bytes (including any shift sequences) written to the character array whose first element is pointed to by `s`. This value may be `​0​`, e.g. when processing the first `char16_t` in a surrogate pair. On failure (if `c16` is not a valid 16-bit character), returns `-1`, stores `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` in `[errno](../../error/errno "cpp/error/errno")`, and leaves `*ps` in unspecified state. ### Notes The C++ standard defers to the C standard for the semantics of this function. In C11 as published, unlike `[std::mbrtoc16](mbrtoc16 "cpp/string/multibyte/mbrtoc16")`, which converts variable-width multibyte (such as UTF-8) to variable-width 16-bit (such as UTF-16) encoding, this function can only convert single-unit 16-bit encoding, meaning it cannot convert UTF-16 to UTF-8 despite that being the original intent of this function. This was corrected by the post-C11 defect report [DR488](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2059.htm#dr_488). ### Example Note: this example assumes the fix for the defect report 488 is applied. ``` #include <iostream> #include <iomanip> #include <string_view> #include <clocale> #include <cuchar> #include <climits> int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::u16string_view strv = u"zß水🍌"; // or z\u00df\u6c34\U0001F34C std::cout << "Processing " << strv.size() << " UTF-16 code units: [ "; for(char16_t c : strv) std::cout << std::showbase << std::hex << static_cast<int>(c) << ' '; std::cout << "]\n"; std::mbstate_t state{}; char out[MB_LEN_MAX]{}; for(char16_t c : strv) { std::size_t rc = std::c16rtomb(out, c, &state); std::cout << static_cast<int>(c) << " converted to [ "; if(rc != (std::size_t)-1) for(unsigned char c8 : std::string_view{out, rc}) std::cout << +c8 << ' '; std::cout << "]\n"; } } ``` Output: ``` Processing 5 UTF-16 code units: [ 0x7a 0xdf 0x6c34 0xd83c 0xdf4c ] 0x7a converted to [ 0x7a ] 0xdf converted to [ 0xc3 0x9f ] 0x6c34 converted to [ 0xe6 0xb0 0xb4 ] 0xd83c converted to [ ] 0xdf4c converted to [ 0xf0 0x9f 0x8d 0x8c ] ``` ### See also | | | | --- | --- | | [mbrtoc16](mbrtoc16 "cpp/string/multibyte/mbrtoc16") (C++11) | Converts a narrow multibyte character to UTF-16 encoding (function) | | [do\_out](../../locale/codecvt/out "cpp/locale/codecvt/out") [virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/c16rtomb "c/string/multibyte/c16rtomb") for `c16rtomb` | cpp std::mbstate_t std::mbstate\_t =============== | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | (since C++17) | | --- | --- | --- | | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | ``` struct mbstate_t; ``` | | | The type mbstate\_t is a trivial non-array type that can represent any of the conversion states that can occur in an implementation-defined set of supported multibyte character encoding rules. Zero-initialized value of `mbstate_t` represents the initial conversion state, although other values of `mbstate_t` may exist that also represent the initial conversion state. Possible implementation of `mbstate_t` is a struct type holding an array representing the incomplete multibyte character, an integer counter indicating the number of bytes in the array that have been processed, and a representation of the current shift state. The following functions should not be called from multiple threads without synchronization with the `std::mbstate_t*` argument of a null pointer due to possible data races: `[std::mbrlen](mbrlen "cpp/string/multibyte/mbrlen")`, `[std::mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc")`, `[std::mbsrtowcs](mbsrtowcs "cpp/string/multibyte/mbsrtowcs")`, `[std::mbtowc](mbtowc "cpp/string/multibyte/mbtowc")`, `[std::wcrtomb](wcrtomb "cpp/string/multibyte/wcrtomb")`, `[std::wcsrtombs](wcsrtombs "cpp/string/multibyte/wcsrtombs")`, `[std::wctomb](wctomb "cpp/string/multibyte/wctomb")`. ### See also | | | | --- | --- | | [mbsinit](mbsinit "cpp/string/multibyte/mbsinit") | checks if the mbstate\_t object represents initial shift state (function) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbstate_t "c/string/multibyte/mbstate t") for `mbstate_t` |
programming_docs
cpp std::wctomb std::wctomb =========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` int wctomb( char *s, wchar_t wc ); ``` | | | Converts a wide character `wc` to multibyte encoding and stores it (including any shift sequences) in the char array whose first element is pointed to by `s`. No more than `MB_CUR_MAX` characters are stored. The conversion is affected by the current locale's LC\_CTYPE category. If `wc` is the null character, the null byte is written to `s`, preceded by any shift sequences necessary to restore the initial shift state. If `s` is a null pointer, resets the global conversion state and determines whether shift sequences are used. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the character array for output | | wc | - | wide character to convert | ### Return value If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte representation of `wc` or `-1` if `wc` is not a valid character. If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and returns `​0​` if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences). ### Notes Each call to `wctomb` updates the internal global conversion state (a static object of type `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")`, only known to this function). If the multibyte encoding uses shift states, this function is not reentrant. In any case, multiple threads should not call `wctomb` without synchronization: `[std::wcrtomb](wcrtomb "cpp/string/multibyte/wcrtomb")` may be used instead. ### Example ``` #include <iostream> #include <iomanip> #include <clocale> #include <string> #include <cstdlib> void print_wide(const std::wstring& wstr) { bool shifts = std::wctomb(nullptr, 0); // reset the conversion state std::cout << "shift sequences are " << (shifts ? "" : "not" ) << " used\n" << std::uppercase << std::setfill('0'); for (const wchar_t wc : wstr) { std::string mb(MB_CUR_MAX, '\0'); const int ret = std::wctomb(&mb[0], wc); const char* s = ret > 1 ? "s" : ""; std::cout << "multibyte char '" << mb << "' is " << ret << " byte" << s << ": [" << std::hex; for (int i{0}; i != ret; ++i) { const int c = 0xFF & mb[i]; std::cout << (i ? " " : "") << std::setw(2) << c; } std::cout << "]\n" << std::dec; } } int main() { std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding std::wstring wstr = L"z\u00df\u6c34\U0001d10b"; // or L"zß水𝄋" print_wide(wstr); } ``` Output: ``` shift sequences are not used multibyte char 'z' is 1 byte: [7A] multibyte char 'ß' is 2 bytes: [C3 9F] multibyte char '水' is 3 bytes: [E6 B0 B4] multibyte char '𝄋' is 4 bytes: [F0 9D 84 8B] ``` ### See also | | | | --- | --- | | [mbtowc](mbtowc "cpp/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) | | [wcrtomb](wcrtomb "cpp/string/multibyte/wcrtomb") | converts a wide character to its multibyte representation, given state (function) | | [do\_out](../../locale/codecvt/out "cpp/locale/codecvt/out") [virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/wctomb "c/string/multibyte/wctomb") for `wctomb` | cpp std::mbrtoc32 std::mbrtoc32 ============= | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | | | --- | --- | --- | | ``` std::size_t mbrtoc32( char32_t* pc32, const char* s, std::size_t n, std::mbstate_t* ps ); ``` | | (since C++11) | Converts a narrow multibyte character to its UTF-32 character representation. If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character in `s` is complete and valid, converts it to the corresponding 32-bit character and stores it in `*pc32` (if `pc32` is not null). If the multibyte character in `*s` corresponds to a multi-char32\_t sequence (not possible with UTF-32), then after the first call to this function, `*ps` is updated in such a way that the next calls to `mbrtoc32` will write out the additional char32\_t, without considering `*s`. If `s` is a null pointer, the values of `n` and `pc32` are ignored and the call is equivalent to `std::mbrtoc32(nullptr, "", 1, ps)`. If the wide character produced is the null character, the conversion state `*ps` represents the initial shift state. The multibyte encoding used by this function is specified by the currently active C locale. ### Parameters | | | | | --- | --- | --- | | pc32 | - | pointer to the location where the resulting 32-bit character will be written | | s | - | pointer to the multibyte character string used as input | | n | - | limit on the number of bytes in s that can be examined | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value The first of the following that applies: * `​0​` if the character converted from `s` (and stored in `*pc32` if non-null) was the null character * the number of bytes `[1...n]` of the multibyte character successfully converted from `s` * `-3` if the next `char32_t` from a multi-`char32_t` character has now been written to `*pc32`. No bytes are processed from the input in this case. * `-2` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pc32`. * `-1` if encoding error occurs. Nothing is written to `*pc32`, the value `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` is stored in `[errno](../../error/errno "cpp/error/errno")` and the value of `*ps` is unspecified. ### Examples ``` #include <iostream> #include <iomanip> #include <clocale> #include <cstring> #include <cwchar> #include <cuchar> #include <cassert> int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::string str = "z\u00df\u6c34\U0001F34C"; // or u8"zß水🍌" std::cout << "Processing " << str.size() << " bytes: [ " << std::showbase; for(unsigned char c: str) std::cout << std::hex << +c << ' '; std::cout << "]\n"; std::mbstate_t state{}; // zero-initialized to initial state char32_t c32; const char *ptr = str.c_str(), *end = str.c_str() + str.size() + 1; while(std::size_t rc = std::mbrtoc32(&c32, ptr, end - ptr, &state)) { std::cout << "Next UTF-32 char: " << std::hex << static_cast<int>(c32) << " obtained from "; assert(rc != (std::size_t)-3); // no surrogates in UTF-32 if(rc == (std::size_t)-1) break; if(rc == (std::size_t)-2) break; std::cout << std::dec << rc << " bytes [ "; for(std::size_t n = 0; n < rc; ++n) std::cout << std::hex << +static_cast<unsigned char>(ptr[n]) << ' '; std::cout << "]\n"; ptr += rc; } } ``` Output: ``` Processing 10 bytes: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c ] Next UTF-32 char: 0x7a obtained from 1 bytes [ 0x7a ] Next UTF-32 char: 0xdf obtained from 2 bytes [ 0xc3 0x9f ] Next UTF-32 char: 0x6c34 obtained from 3 bytes [ 0xe6 0xb0 0xb4 ] Next UTF-32 char: 0x1f34c obtained from 4 bytes [ 0xf0 0x9f 0x8d 0x8c ] ``` ### See also | | | | --- | --- | | [c32rtomb](c32rtomb "cpp/string/multibyte/c32rtomb") (C++11) | convert a 32-bit wide character to narrow multibyte string (function) | | [do\_in](../../locale/codecvt/in "cpp/locale/codecvt/in") [virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbrtoc32 "c/string/multibyte/mbrtoc32") for `mbrtoc32` | cpp std::mbstowcs std::mbstowcs ============= | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` std::size_t mbstowcs( wchar_t* dst, const char* src, std::size_t len); ``` | | | Converts a multibyte character string from the array whose first element is pointed to by `src` to its wide character representation. Converted characters are stored in the successive elements of the array pointed to by `dst`. No more than `len` wide characters are written to the destination array. Each character is converted as if by a call to `[std::mbtowc](mbtowc "cpp/string/multibyte/mbtowc")`, except that the mbtowc conversion state is unaffected. The conversion stops if: * The multibyte null character was converted and stored. * An invalid (in the current C locale) multibyte character was encountered. * The next wide character to be stored would exceed `len`. ### Notes In most implementations, this function updates a global static object of type `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")` as it processes through the string, and cannot be called simultaneously by two threads, `[std::mbsrtowcs](mbsrtowcs "cpp/string/multibyte/mbsrtowcs")` should be used in such cases. POSIX specifies a common extension: if `dst` is a null pointer, this function returns the number of wide characters that would be written to `dst`, if converted. Similar behavior is standard for `[std::mbsrtowcs](mbsrtowcs "cpp/string/multibyte/mbsrtowcs")`. ### Parameters | | | | | --- | --- | --- | | dst | - | pointer to wide character array where the wide string will be stored | | src | - | pointer to the first element of a null-terminated multibyte string to convert | | len | - | number of wide characters available in the array pointed to by dst | ### Return value On success, returns the number of wide characters, excluding the terminating `L'\0'`, written to the destination array. On conversion error (if invalid multibyte character was encountered), returns `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)> (-1)`. ### Example ``` #include <iostream> #include <clocale> #include <cstdlib> int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::wcout.imbue(std::locale("en_US.utf8")); const char* mbstr = "z\u00df\u6c34\U0001f34c"; // or u8"zß水🍌" // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c"; wchar_t wstr[5]; std::mbstowcs(wstr, mbstr, 5); std::wcout << "wide string: " << wstr << '\n'; } ``` Output: ``` wide string: zß水🍌 ``` ### See also | | | | --- | --- | | [mbsrtowcs](mbsrtowcs "cpp/string/multibyte/mbsrtowcs") | converts a narrow multibyte character string to wide string, given state (function) | | [wcstombs](wcstombs "cpp/string/multibyte/wcstombs") | converts a wide string to narrow multibyte character string (function) | | [do\_in](../../locale/codecvt/in "cpp/locale/codecvt/in") [virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbstowcs "c/string/multibyte/mbstowcs") for `mbstowcs` | cpp std::wcstombs std::wcstombs ============= | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` std::size_t wcstombs( char* dst, const wchar_t* src, std::size_t len); ``` | | | Converts a sequence of wide characters from the array whose first element is pointed to by `src` to its narrow multibyte representation that begins in the initial shift state. Converted characters are stored in the successive elements of the char array pointed to by `dst`. No more than `len` bytes are written to the destination array. Each character is converted as if by a call to `[std::wctomb](wctomb "cpp/string/multibyte/wctomb")`, except that the wctomb's conversion state is unaffected. The conversion stops if: * The null character was converted and stored. * A `wchar_t` was found that does not correspond to a valid character in the current C locale. * The next multibyte character to be stored would exceed `len`. ### Notes In most implementations, this function updates a global static object of type `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")` as it processes through the string, and cannot be called simultaneously by two threads, `[std::wcsrtombs](http://en.cppreference.com/w/cpp/string/multibyte/wcsrtombs)` should be used in such cases. POSIX specifies a common extension: if `dst` is a null pointer, this function returns the number of bytes that would be written to `dst`, if converted. Similar behavior is standard for `[std::wcsrtombs](http://en.cppreference.com/w/cpp/string/multibyte/wcsrtombs)`. ### Parameters | | | | | --- | --- | --- | | dst | - | pointer to narrow character array where the multibyte character will be stored | | src | - | pointer to the first element of a null-terminated wide string to convert | | len | - | number of byte available in the array pointed to by dst | ### Return value On success, returns the number of bytes (including any shift sequences, but excluding the terminating `'\0'`) written to the character array whose first element is pointed to by `dst`. On conversion error (if invalid wide character was encountered), returns `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)`. ### Example ``` #include <iostream> #include <clocale> #include <cstdlib> int main() { std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding const wchar_t* wstr = L"z\u00df\u6c34\U0001d10b"; // or L"zß水𝄋" char mbstr[11]; std::wcstombs(mbstr, wstr, 11); std::cout << "multibyte string: " << mbstr << '\n'; } ``` Output: ``` multibyte string: zß水𝄋 ``` ### See also | | | | --- | --- | | [wcsrtombs](wcsrtombs "cpp/string/multibyte/wcsrtombs") | converts a wide string to narrow multibyte character string, given state (function) | | [mbstowcs](mbstowcs "cpp/string/multibyte/mbstowcs") | converts a narrow multibyte character string to wide string (function) | | [do\_out](../../locale/codecvt/out "cpp/locale/codecvt/out") [virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/wcstombs "c/string/multibyte/wcstombs") for `wcstombs` | cpp std::mblen std::mblen ========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` int mblen( const char* s, std::size_t n ); ``` | | | Determines the size, in bytes, of the multibyte character whose first byte is pointed to by `s`. If `s` is a null pointer, resets the global conversion state and determines whether shift sequences are used. This function is equivalent to the call `[std::mbtowc](http://en.cppreference.com/w/cpp/string/multibyte/mbtowc)(nullptr, s, n)`, except that conversion state of `[std::mbtowc](mbtowc "cpp/string/multibyte/mbtowc")` is unaffected. ### Notes Each call to `mblen` updates the internal global conversion state (a static object of type `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")`, only known to this function). If the multibyte encoding uses shift states, care must be taken to avoid backtracking or multiple scans. In any case, multiple threads should not call `mblen` without synchronization: `[std::mbrlen](mbrlen "cpp/string/multibyte/mbrlen")` may be used instead. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the multibyte character | | n | - | limit on the number of bytes in s that can be examined | ### Return value If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte character or `-1` if the first bytes pointed to by `s` do not form a valid multibyte character or `​0​` if `s` is pointing at the null charcter `'\0'`. If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and returns `​0​` if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences). ### Example ``` #include <clocale> #include <cstdlib> #include <iomanip> #include <iostream> #include <stdexcept> #include <string_view> // the number of characters in a multibyte string is the sum of mblen()'s // note: the simpler approach is std::mbstowcs(nullptr, s.c_str(), s.size()) std::size_t strlen_mb(const std::string_view s) { std::size_t result = 0; const char* ptr = s.data(); const char* end = ptr + s.size(); std::mblen(nullptr, 0); // reset the conversion state while (ptr < end) { int next = std::mblen(ptr, end-ptr); if (next == -1) { throw std::runtime_error("strlen_mb(): conversion error"); } ptr += next; ++result; } return result; } void dump_bytes(const std::string_view str) { std::cout << std::hex << std::uppercase << std::setfill('0'); for (unsigned char c : str) std::cout << std::setw(2) << static_cast<int>(c) << ' '; std::cout << std::dec << '\n'; } int main() { // allow mblen() to work with UTF-8 multibyte encoding std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding const std::string_view str = "z\u00df\u6c34\U0001f34c"; // or u8"zß水🍌" std::cout << std::quoted(str) << " is " << strlen_mb(str) << " characters, but as much as " << str.size() << " bytes: "; dump_bytes(str); } ``` Possible output: ``` "zß水🍌" is 4 characters, but as much as 10 bytes: 7A C3 9F E6 B0 B4 F0 9F 8D 8C ``` ### See also | | | | --- | --- | | [mbtowc](mbtowc "cpp/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) | | [mbrlen](mbrlen "cpp/string/multibyte/mbrlen") | returns the number of bytes in the next multibyte character, given state (function) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mblen "c/string/multibyte/mblen") for `mblen` | cpp std::wctob std::wctob ========== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` int wctob( std::wint_t c ); ``` | | | Narrows a wide character `c` if its multibyte character equivalent in the initial shift state is a single byte. This is typically possible for the characters from the ASCII character set, since most multibyte encodings (such as UTF-8) use single bytes to encode those characters. ### Parameters | | | | | --- | --- | --- | | c | - | wide character to narrow | ### Return value `[EOF](../../io/c "cpp/io/c")` if `c` does not represent a multibyte character with length `1` in initial shift state. Otherwise, the single-byte representation of `c` as `unsigned char` converted to `int`. ### Example ``` #include <clocale> #include <cwchar> #include <iostream> void try_narrowing(wchar_t c) { int cn = std::wctob(c); if(cn != EOF) std::cout << '\'' << int(c) << "' narrowed to " << +cn << '\n'; else std::cout << '\'' << int(c) << "' could not be narrowed\n"; } int main() { std::setlocale(LC_ALL, "th_TH.utf8"); std::cout << std::hex << std::showbase << "In Thai UTF-8 locale:\n"; try_narrowing(L'a'); try_narrowing(L'๛'); std::setlocale(LC_ALL, "th_TH.tis620"); std::cout << "In Thai TIS-620 locale:\n"; try_narrowing(L'a'); try_narrowing(L'๛'); } ``` Output: ``` In Thai UTF-8 locale: '0x61' narrowed to 0x61 '0xe5b' could not be narrowed In Thai TIS-620 locale: '0x61' narrowed to 0x61 '0xe5b' narrowed to 0xfb ``` ### See also | | | | --- | --- | | [btowc](btowc "cpp/string/multibyte/btowc") | widens a single-byte narrow character to wide character, if possible (function) | | [narrow](../../io/basic_ios/narrow "cpp/io/basic ios/narrow") | narrows characters (public member function of `std::basic_ios<CharT,Traits>`) | | [narrow](../../locale/ctype/narrow "cpp/locale/ctype/narrow") | invokes `do_narrow` (public member function of `std::ctype<CharT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/wctob "c/string/multibyte/wctob") for `wctob` |
programming_docs
cpp std::mbsrtowcs std::mbsrtowcs ============== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t mbsrtowcs( wchar_t* dst, const char** src, std::size_t len, std::mbstate_t* ps ); ``` | | | Converts a null-terminated multibyte character sequence, which begins in the conversion state described by `*ps`, from the array whose first element is pointed to by `*src` to its wide character representation. If `dst` is not null, converted characters are stored in the successive elements of the wchar\_t array pointed to by `dst`. No more than `len` wide characters are written to the destination array. Each multibyte character is converted as if by a call to `[std::mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc")`. The conversion stops if: * The multibyte null character was converted and stored. `src` is set to a null pointer and `*ps` represents the initial shift state. * An invalid multibyte character (according to the current C locale) was encountered. `src` is set to point at the beginning of the first unconverted multibyte character. * the next wide character to be stored would exceed `len`. `src` is set to point at the beginning of the first unconverted multibyte character. This condition is not checked if `dst` is a null pointer. ### Parameters | | | | | --- | --- | --- | | dst | - | pointer to wide character array where the results will be stored | | src | - | pointer to pointer to the first element of a null-terminated multibyte string | | len | - | number of wide characters available in the array pointed to by dst | | ps | - | pointer to the conversion state object | ### Return value On success, returns the number of wide characters, excluding the terminating `L'\0'`, written to the character array. If `dst` is a null pointer, returns the number of wide characters that would have been written given unlimited length. On conversion error (if invalid multibyte character was encountered), returns `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)`, stores `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` in `[errno](../../error/errno "cpp/error/errno")`, and leaves `*ps` in unspecified state. ### Notes This function moves the `src` pointer to the end of the converted multibyte string. This doesn't happen if `dst` is a null pointer. ### Example ``` #include <iostream> #include <vector> #include <clocale> #include <cwchar> void print_as_wide(const char* mbstr) { std::mbstate_t state = std::mbstate_t(); std::size_t len = 1 + std::mbsrtowcs(nullptr, &mbstr, 0, &state); std::vector<wchar_t> wstr(len); std::mbsrtowcs(&wstr[0], &mbstr, wstr.size(), &state); std::wcout << "Wide string: " << &wstr[0] << '\n' << "The length, including '\\0': " << wstr.size() << '\n'; } int main() { std::setlocale(LC_ALL, "en_US.utf8"); const char* mbstr = "z\u00df\u6c34\U0001f34c"; // or u8"zß水🍌" print_as_wide(mbstr); } ``` Output: ``` Wide string: zß水🍌 The length, including '\0': 5 ``` ### See also | | | | --- | --- | | [mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc") | converts the next multibyte character to wide character, given state (function) | | [wcsrtombs](wcsrtombs "cpp/string/multibyte/wcsrtombs") | converts a wide string to narrow multibyte character string, given state (function) | | [do\_in](../../locale/codecvt/in "cpp/locale/codecvt/in") [virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbsrtowcs "c/string/multibyte/mbsrtowcs") for `mbsrtowcs` | cpp std::mbtowc std::mbtowc =========== | Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` int mbtowc( wchar_t* pwc, const char* s, std::size_t n ); ``` | | | Converts a multibyte character whose first byte is pointed to by `s` to a wide character, written to `*pwc` if `pwc` is not null. If `s` is a null pointer, resets the global conversion state and determines whether shift sequences are used. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to the multibyte character | | n | - | limit on the number of bytes in s that can be examined | | pwc | - | pointer to the wide character for output | ### Return value If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte character or `-1` if the first bytes pointed to by `s` do not form a valid multibyte character or `​0​` if `s` is pointing at the null charcter `'\0'`. If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and returns `​0​` if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences). ### Notes Each call to `mbtowc` updates the internal global conversion state (a static object of type `[std::mbstate\_t](mbstate_t "cpp/string/multibyte/mbstate t")`, only known to this function). If the multibyte encoding uses shift states, care must be taken to avoid backtracking or multiple scans. In any case, multiple threads should not call `mbtowc` without synchronization: `[std::mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc")` may be used instead. ### Example ``` #include <iostream> #include <clocale> #include <cstring> #include <cstdlib> int print_mb(const char* ptr) { std::mbtowc(nullptr, 0, 0); // reset the conversion state const char* end = ptr + std::strlen(ptr); int ret; for (wchar_t wc; (ret = std::mbtowc(&wc, ptr, end-ptr)) > 0; ptr+=ret) { std::wcout << wc; } std::wcout << '\n'; return ret; } int main() { std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding const char* str = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋" // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; print_mb(str); } ``` Output: ``` zß水𝄋 ``` ### See also | | | | --- | --- | | [mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc") | converts the next multibyte character to wide character, given state (function) | | [mblen](mblen "cpp/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) | | [do\_in](../../locale/codecvt/in "cpp/locale/codecvt/in") [virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbtowc "c/string/multibyte/mbtowc") for `mbtowc` | cpp std::c8rtomb std::c8rtomb ============ | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | | | --- | --- | --- | | ``` std::size_t c8rtomb( char* s, char8_t c8, std::mbstate_t* ps ); ``` | | (since C++20) | Converts a single code point from UTF-8 to a narrow multibyte character representation. If `s` is not a null pointer and `c8` is the last code unit in a valid UTF-8 encoding of a code point, the function determines the number of bytes necessary to store the multibyte character representation of that code point (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function. If `c8` is not the final UTF-8 code unit in a representation of a code point, the function does not write to the array pointed to by `s`, only `*ps` is updated. If `s` is a null pointer, the call is equivalent to `std::c8rtomb(buf, u8'\0', ps)` for some internal buffer `buf`. If `c8` is the null character `u8'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state. The multibyte encoding used by this function is specified by the currently active C locale. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to narrow character array where the multibyte character will be stored | | c8 | - | the UTF-8 code unit to convert | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value The number of bytes stored in the array object (including any shift sequences). This may be zero when `c8` is not the final code unit in the UTF-8 representation of a code point. If `c8` is invalid (does not contribute to a sequence of `char8_t` corresponding to a valid multibyte character), the value of the macro `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` is stored in `[errno](../../error/errno "cpp/error/errno")`, `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)` is returned, and the conversion state is unspecified. ### Notes Calls to `c8rtomb` with a null pointer argument for `s` may introduce a data race with other calls to `c8rtomb` with a null pointer argument for `s`. ### Example ### See also | | | | --- | --- | | [mbrtoc8](mbrtoc8 "cpp/string/multibyte/mbrtoc8") (C++20) | converts a narrow multibyte character to UTF-8 encoding (function) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/c8rtomb "c/string/multibyte/c8rtomb") for `c8rtomb` | cpp std::mbrtoc8 std::mbrtoc8 ============ | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | | | --- | --- | --- | | ``` std::size_t mbrtoc8( char8_t* pc8, const char* s, std::size_t n, std::mbstate_t* ps ); ``` | | (since C++20) | Converts a narrow multibyte character to UTF-8 encoding. If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character in `s` is complete and valid, converts it to UTF-8 and stores the first UTF-8 code unit in `*pc8` (if `pc8` is not null). If UTF-8 encoding of the multibyte character in `*s` consists of more than one UTF-8 code unit, then after the first call to this function, `*ps` is updated in such a way that the next call to `mbrtoc8` will write out the additional UTF-8 code units, without considering `*s`. If `s` is a null pointer, the values of `n` and `pc8` are ignored and the call is equivalent to `std::mbrtoc8(nullptr, "", 1, ps)`. If UTF-8 code unit produced is `u8'\0'`, the conversion state `*ps` represents the initial shift state. The multibyte encoding used by this function is specified by the currently active C locale. ### Parameters | | | | | --- | --- | --- | | pc8 | - | pointer to the location where the resulting UTF-8 code units will be written | | s | - | pointer to the multibyte character string used as input | | n | - | limit on the number of bytes in s that can be examined | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value The first of the following that applies: * `​0​` if the character converted from `s` (and stored in `*pc8` if non-null) was the null character * the number of bytes `[1...n]` of the multibyte character successfully converted from `s` * `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-3)` if the next UTF-8 code unit from a character whose encoding consists of multiple code units has now been written to `*pc8`. No bytes are processed from the input in this case. * `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-2)` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pc8`. * `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)` if encoding error occurs. Nothing is written to `*pc8`, the value `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` is stored in `[errno](../../error/errno "cpp/error/errno")` and the value of `*ps` is unspecified. ### Example ### See also | | | | --- | --- | | [c8rtomb](c8rtomb "cpp/string/multibyte/c8rtomb") (C++20) | converts UTF-8 string to narrow multibyte encoding (function) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbrtoc8 "c/string/multibyte/mbrtoc8") for `mbrtoc8` | cpp std::wcrtomb std::wcrtomb ============ | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t wcrtomb( char* s, wchar_t wc, std::mbstate_t* ps ); ``` | | | Converts a wide character to its narrow multibyte representation. If `s` is not a null pointer, the function determines the number of bytes necessary to store the multibyte character representation of `wc` (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function. If `s` is a null pointer, the call is equivalent to `std::wcrtomb(buf, L'\0', ps)` for some internal buffer `buf`. If wc is the null wide character `L'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to narrow character array where the multibyte character will be stored | | wc | - | the wide character to convert | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value On success, returns the number of bytes (including any shift sequences) written to the character array whose first element is pointed to by `s`. On failure (if `wc` is not a valid wide character), returns `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)`, stores `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` in `[errno](../../error/errno "cpp/error/errno")`, and leaves `*ps` in unspecified state. ### Example ``` #include <iostream> #include <clocale> #include <string> #include <cwchar> void print_wide(const std::wstring& wstr) { std::mbstate_t state {}; for(wchar_t wc : wstr) { std::string mb(MB_CUR_MAX, '\0'); std::size_t ret = std::wcrtomb(&mb[0], wc, &state); std::cout << "multibyte char " << mb << " is " << ret << " bytes\n"; } } int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::wstring wstr = L"z\u00df\u6c34\U0001f34c"; // or L"zß水🍌" print_wide(wstr); } ``` Output: ``` multibyte char z is 1 bytes multibyte char ß is 2 bytes multibyte char 水 is 3 bytes multibyte char 🍌 is 4 bytes ``` ### See also | | | | --- | --- | | [wctomb](wctomb "cpp/string/multibyte/wctomb") | converts a wide character to its multibyte representation (function) | | [mbrtowc](mbrtowc "cpp/string/multibyte/mbrtowc") | converts the next multibyte character to wide character, given state (function) | | [do\_out](../../locale/codecvt/out "cpp/locale/codecvt/out") [virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/wcrtomb "c/string/multibyte/wcrtomb") for `wcrtomb` | cpp std::c32rtomb std::c32rtomb ============= | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | | | --- | --- | --- | | ``` std::size_t c32rtomb( char* s, char32_t c32, std::mbstate_t* ps ); ``` | | (since C++11) | Converts a UTF-32 character to its narrow multibyte representation. If `s` is not a null pointer, the function determines the number of bytes necessary to store the multibyte character representation of `c32` (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function. If `s` is a null pointer, the call is equivalent to `std::c32rtomb(buf, U'\0', ps)` for some internal buffer `buf`. If c32 is the null wide character `U'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state. The multibyte encoding used by this function is specified by the currently active C locale. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to narrow character array where the multibyte character will be stored | | c32 | - | the 32-bit character to convert | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value On success, returns the number of bytes (including any shift sequences) written to the character array whose first element is pointed to by `s`. This value may be `​0​`, e.g. when processing the first `char32_t` in multi-`char32_t`-character sequence (does not occur in UTF-32). On failure (if `c32` is not a valid 32-bit character), returns `-1`, stores `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` in `[errno](../../error/errno "cpp/error/errno")`, and leaves `*ps` in unspecified state. ### Example ``` #include <iostream> #include <iomanip> #include <string_view> #include <clocale> #include <cuchar> #include <climits> int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::u32string_view strv = U"zß水🍌"; // or z\u00df\u6c34\U0001F34C std::cout << "Processing " << strv.size() << " UTF-32 code units: [ "; for(char32_t c : strv) std::cout << std::showbase << std::hex << static_cast<int>(c) << ' '; std::cout << "]\n"; std::mbstate_t state{}; char out[MB_LEN_MAX]{}; for(char32_t c : strv) { std::size_t rc = std::c32rtomb(out, c, &state); std::cout << static_cast<int>(c) << " converted to [ "; if(rc != (std::size_t)-1) for(unsigned char c8 : std::string_view{out, rc}) std::cout << +c8 << ' '; std::cout << "]\n"; } } ``` Output: ``` Processing 4 UTF-32 code units: [ 0x7a 0xdf 0x6c34 0x1f34c ] 0x7a converted to [ 0x7a ] 0xdf converted to [ 0xc3 0x9f ] 0x6c34 converted to [ 0xe6 0xb0 0xb4 ] 0x1f34c converted to [ 0xf0 0x9f 0x8d 0x8c ] ``` ### See also | | | | --- | --- | | [mbrtoc32](mbrtoc32 "cpp/string/multibyte/mbrtoc32") (C++11) | converts a narrow multibyte character to UTF-32 encoding (function) | | [do\_out](../../locale/codecvt/out "cpp/locale/codecvt/out") [virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/c32rtomb "c/string/multibyte/c32rtomb") for `c32rtomb` | cpp std::wcsrtombs std::wcsrtombs ============== | Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | | | --- | --- | --- | | ``` std::size_t wcsrtombs( char* dst, const wchar_t** src, std::size_t len, std::mbstate_t* ps ); ``` | | | Converts a sequence of wide characters from the array whose first element is pointed to by `*src` to its narrow multibyte representation that begins in the conversion state described by `*ps`. If `dst` is not null, converted characters are stored in the successive elements of the char array pointed to by `dst`. No more than `len` bytes are written to the destination array. Each character is converted as if by a call to `[std::wcrtomb](wcrtomb "cpp/string/multibyte/wcrtomb")`. The conversion stops if: * The null character was converted and stored. `src` is set to a null pointer and `*ps` represents the initial shift state. * A `wchar_t` was found that does not correspond to a valid character in the current C locale. `src` is set to point at the first unconverted wide character. * the next multibyte character to be stored would exceed `len`. `src` is set to point at the first unconverted wide character. This condition is not checked if `dst` is a null pointer. ### Parameters | | | | | --- | --- | --- | | dst | - | pointer to narrow character array where the multibyte characters will be stored | | src | - | pointer to pointer to the first element of a null-terminated wide string | | len | - | number of bytes available in the array pointed to by dst | | ps | - | pointer to the conversion state object | ### Return value On success, returns the number of bytes (including any shift sequences, but excluding the terminating `'\0'`) written to the character array whose first element is pointed to by `dst`. If `dst` is a null pointer, returns the number of bytes that would have been written (again, excluding the terminating null character `'\0'`). On conversion error (if invalid wide character was encountered), returns `static\_cast<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(-1)`, stores `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` in `[errno](../../error/errno "cpp/error/errno")`, and leaves `*ps` in unspecified state. ### Example ``` #include <iostream> #include <vector> #include <clocale> #include <string> #include <cwchar> void print_wide(const wchar_t* wstr) { std::mbstate_t state = std::mbstate_t(); std::size_t len = 1 + std::wcsrtombs(nullptr, &wstr, 0, &state); std::vector<char> mbstr(len); std::wcsrtombs(&mbstr[0], &wstr, mbstr.size(), &state); std::cout << "multibyte string: " << &mbstr[0] << '\n' << "Length, including '\\0': " << mbstr.size() << '\n'; } int main() { std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding const wchar_t* wstr = L"z\u00df\u6c34\U0001d10b"; // or L"zß水𝄋" print_wide(wstr); } ``` Output: ``` multibyte string: zß水𝄋 Length, including '\0': 11 ``` ### See also | | | | --- | --- | | [wcrtomb](wcrtomb "cpp/string/multibyte/wcrtomb") | converts a wide character to its multibyte representation, given state (function) | | [mbsrtowcs](mbsrtowcs "cpp/string/multibyte/mbsrtowcs") | converts a narrow multibyte character string to wide string, given state (function) | | [do\_out](../../locale/codecvt/out "cpp/locale/codecvt/out") [virtual] | converts a string from `InternT` to `ExternT`, such as when writing to file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/wcsrtombs "c/string/multibyte/wcsrtombs") for `wcsrtombs` |
programming_docs
cpp std::mbrtoc16 std::mbrtoc16 ============= | Defined in header `[<cuchar>](../../header/cuchar "cpp/header/cuchar")` | | | | --- | --- | --- | | ``` std::size_t mbrtoc16( char16_t* pc16, const char* s, std::size_t n, std::mbstate_t* ps ); ``` | | (since C++11) | Converts a narrow multibyte character to UTF-16 character representation. If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character in `s` is complete and valid, converts it to the corresponding 16-bit character and stores it in `*pc16` (if `pc16` is not null). If the multibyte character in `*s` corresponds to a multi-char16\_t sequence (e.g. a surrogate pair in UTF-16), then after the first call to this function, `*ps` is updated in such a way that the next call to `mbrtoc16` will write out the additional char16\_t, without considering `*s`. If `s` is a null pointer, the values of `n` and `pc16` are ignored and the call is equivalent to `std::mbrtoc16(nullptr, "", 1, ps)`. If the wide character produced is the null character, the conversion state `*ps` represents the initial shift state. The multibyte encoding used by this function is specified by the currently active C locale. ### Parameters | | | | | --- | --- | --- | | pc16 | - | pointer to the location where the resulting 16-bit character will be written | | s | - | pointer to the multibyte character string used as input | | n | - | limit on the number of bytes in s that can be examined | | ps | - | pointer to the conversion state object used when interpreting the multibyte string | ### Return value The first of the following that applies: * `​0​` if the character converted from `s` (and stored in `*pc16` if non-null) was the null character * the number of bytes `[1...n]` of the multibyte character successfully converted from `s` * `-3` if the next `char16_t` from a multi-`char16_t` character (e.g. a surrogate pair) has now been written to `*pc16`. No bytes are processed from the input in this case. * `-2` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pc16`. * `-1` if encoding error occurs. Nothing is written to `*pc16`, the value `[EILSEQ](../../error/errno_macros "cpp/error/errno macros")` is stored in `[errno](../../error/errno "cpp/error/errno")` and the value of `*ps` is unspecified. ### Example ``` #include <iostream> #include <iomanip> #include <clocale> #include <cstring> #include <cwchar> #include <cuchar> int main() { std::setlocale(LC_ALL, "en_US.utf8"); std::string str = "z\u00df\u6c34\U0001F34C"; // or u8"zß水🍌" std::cout << "Processing " << str.size() << " bytes: [ " << std::showbase; for(unsigned char c: str) std::cout << std::hex << +c << ' '; std::cout << "]\n"; std::mbstate_t state{}; // zero-initialized to initial state char16_t c16; const char *ptr = &str[0], *end = &str[0] + str.size(); while(std::size_t rc = std::mbrtoc16(&c16, ptr, end - ptr + 1, &state)) { std::cout << "Next UTF-16 char: " << std::hex << static_cast<int>(c16) << " obtained from "; if(rc == (std::size_t)-3) std::cout << "earlier surrogate pair\n"; else if(rc == (std::size_t)-2) break; else if(rc == (std::size_t)-1) break; else { std::cout << std::dec << rc << " bytes [ "; for(std::size_t n = 0; n < rc; ++n) std::cout << std::hex << +static_cast<unsigned char>(ptr[n]) << ' '; std::cout << "]\n"; ptr += rc; } } } ``` Output: ``` Processing 10 bytes: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c ] Next UTF-16 char: 0x7a obtained from 1 bytes [ 0x7a ] Next UTF-16 char: 0xdf obtained from 2 bytes [ 0xc3 0x9f ] Next UTF-16 char: 0x6c34 obtained from 3 bytes [ 0xe6 0xb0 0xb4 ] Next UTF-16 char: 0xd83c obtained from 4 bytes [ 0xf0 0x9f 0x8d 0x8c ] Next UTF-16 char: 0xdf4c obtained from earlier surrogate pair ``` ### See also | | | | --- | --- | | [c16rtomb](c16rtomb "cpp/string/multibyte/c16rtomb") (C++11) | convert a 16-bit wide character to narrow multibyte string (function) | | [do\_in](../../locale/codecvt/in "cpp/locale/codecvt/in") [virtual] | converts a string from `ExternT` to `InternT`, such as when reading from file (virtual protected member function of `std::codecvt<InternT,ExternT,StateT>`) | | [C documentation](https://en.cppreference.com/w/c/string/multibyte/mbrtoc16 "c/string/multibyte/mbrtoc16") for `mbrtoc16` | cpp Compiler support for C++23 Compiler support for C++23 ========================== ### C++23 core language features | C++23 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | [Literal suffix](../language/integer_literal "cpp/language/integer literal") for (signed) [`size_t`](../types/size_t "cpp/types/size t") | [P0330R8](https://wg21.link/P0330R8) | 11 | 13 | | 13.1.6\* | | | | | | | | | | Make `()` more optional for [lambdas](../language/lambda "cpp/language/lambda") | [P1102R2](https://wg21.link/P1102R2) | 11 | 13 | | 13.1.6\* | 6.3 | | | | | | | | | [`if consteval`](../language/if#Consteval_if "cpp/language/if") | [P1938R3](https://wg21.link/P1938R3) | 12 | 14 | | 14.0.0\* | 6.3 | | | | | | | | | Removing Garbage Collection Support | [P2186R2](https://wg21.link/P2186R2) | 12 | | | | N/A | | | | | | | | | DR: C++ Identifier Syntax using Unicode Standard Annex 31 | [P1949R7](https://wg21.link/P1949R7) | 12 | 14 | | 14.0.0\* | 6.4 | | | | | | | | | DR: Allow Duplicate Attributes | [P2156R1](https://wg21.link/P2156R1) | 11 | 13 | | 13.1.6\* | | | | | | | | | | Narrowing contextual conversions in [`static_assert`](../language/static_assert "cpp/language/static assert") and [constexpr if](../language/if#Constexpr_if "cpp/language/if") | [P1401R5](https://wg21.link/P1401R5) | 9 | 13 (partial)\*14 | | 14.0.0\* | | | | | | | | | | Trimming whitespaces before line splicing | [P2223R2](https://wg21.link/P2223R2) | Yes | Yes | | Yes | | | | | | | | | | Make declaration order layout mandated | [P1847R4](https://wg21.link/P1847R4) | Yes | Yes | Yes | Yes | | | | | | | | | | Removing mixed wide [string literal concatenation](../language/string_literal#Concatenation "cpp/language/string literal") | [P2201R1](https://wg21.link/P2201R1) | Yes | Yes | Yes | Yes | Yes | Yes | | | | | | | | [Deducing this](../language/member_functions#Explicit_object_parameter "cpp/language/member functions") | [P0847R7](https://wg21.link/P0847R7) | | | 19.32\*(partial)\* | | 6.3 | | | | | | | | | [`auto(x)` and `auto{x}`](../language/explicit_cast "cpp/language/explicit cast") | [P0849R8](https://wg21.link/P0849R8) | 12 | 15 | | | 6.4 | | | | | | | | | Change scope of lambda trailing-return-type | [P2036R3](https://wg21.link/P2036R3) | | | | | | | | | | | | | | [`#elifdef` and `#elifndef`](../preprocessor/conditional "cpp/preprocessor/conditional") | [P2334R1](https://wg21.link/P2334R1) | 12 | 13 | | 13.1.6\* | | | | | | | | | | Non-literal variables (and labels and gotos) in [`constexpr`](../language/constexpr "cpp/language/constexpr") functions | [P2242R3](https://wg21.link/P2242R3) | 12 | 15 | | | 6.3 | | | | | | | | | Consistent character literal encoding | [P2316R2](https://wg21.link/P2316R2) | Yes | Yes | | Yes | Yes | | | | | | | | | Character sets and encodings | [P2314R4](https://wg21.link/P2314R4) | | Yes | | Yes | | | | | | | | | | Extend init-statement to allow alias-declaration | [P2360R0](https://wg21.link/P2360R0) | 12 | 14 | | 14.0.0\* | | | | | | | | | | Multidimensional subscript operator | [P2128R6](https://wg21.link/P2128R6) | 12 | 15 | | | | | | | | | | | | Attributes on [lambdas](../language/lambda "cpp/language/lambda") | [P2173R1](https://wg21.link/P2173R1) | 9 | 13 | | 13.1.6\* | | | | | | | | | | DR: Adjusting the value of feature testing macro `__cpp_concepts` | [P2493R0](https://wg21.link/P2493R0) | 12 | | 19.32\* | | 6.4 | | | | | | | | | [`#warning`](../preprocessor/error "cpp/preprocessor/error") | [P2437R1](https://wg21.link/P2437R1) | Yes\* | Yes | | Yes | Yes | Yes | | | | | | | | Remove non-encodable wide character literals and multicharacter wide character literals | [P2362R3](https://wg21.link/P2362R3) | 13 | 14 | | | | | | | | | | | | Labels at the end of compound statements | [P2324R2](https://wg21.link/P2324R2) | 13 | | | | | | | | | | | | | Delimited escape sequences | [P2290R3](https://wg21.link/P2290R3) | 13 | 15 | | | | | | | | | | | | Named universal character escapes | [P2071R2](https://wg21.link/P2071R2) | 13 | 15 | | | | | | | | | | | | Relaxing some `constexpr` restrictions | [P2448R2](https://wg21.link/P2448R2) | | | | | | | | | | | | | | Simpler implicit move | [P2266R3](https://wg21.link/P2266R3) | | 13 | | | | | | | | | | | | `static operator()` | [P1169R4](https://wg21.link/P1169R4) | | | | | | | | | | | | | | Requirements for optional extended floating-point types | [P1467R9](https://wg21.link/P1467R9) | | | N/A | | | | | | | | | | | Class template argument deduction from inherited constructors | [P2582R1](https://wg21.link/P2582R1) | | | | | | | | | | | | | | Attribute `[[[assume](https://en.cppreference.com/mwiki/index.php?title=cpp/language/attributes/assume&action=edit&redlink=1 "cpp/language/attributes/assume (page does not exist)")]]` | [P1774R8](https://wg21.link/P1774R8) | | | | | | | | | | | | | | Support for UTF-8 as a portable source file encoding | [P2295R6](https://wg21.link/P2295R6) | | 15\* | | | | | | | | | | | | DR: De-deprecating volatile bitwise compound assignment operations | [P2327R1](https://wg21.link/P2327R1) | 13 | 15 | | | | | | | | | | | | DR: Relax requirements on `wchar_t` to match existing practices | [P2460R2](https://wg21.link/P2460R2) | Yes | Yes | | | | | | | | | | | | DR: Using unknown pointers and references in constant expressions | [P2280R4](https://wg21.link/P2280R4) | | | | | | | | | | | | | | DR: The Equality Operator You Are Looking For | [P2468R2](https://wg21.link/P2468R2) | | | | | | | | | | | | | | DR: `char8_t` Compatibility and Portability Fix | [P2513R3](https://wg21.link/P2513R3) | | | | | | | | | | | | | | C++23 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc | ### C++23 library features | C++23 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | [Stacktrace library](../error#Stacktrace "cpp/error") | [P0881R7](https://wg21.link/P0881R7)[P2301R1](https://wg21.link/P2301R1) | 12 (partial)\* | | 19.34\* | | | | | | [`<stdatomic.h>`](../header/stdatomic.h "cpp/header/stdatomic.h") | [P0943R6](https://wg21.link/P0943R6) | 12 | 15 | 19.31\* | | | | | | [`std::is_scoped_enum`](../types/is_scoped_enum "cpp/types/is scoped enum") | [P1048R1](https://wg21.link/P1048R1) | 11 | 12 | 19.30\* | 13.0.0\* | | | | | [`basic_string::contains()`](../string/basic_string/contains "cpp/string/basic string/contains"), [`basic_string_view::contains()`](../string/basic_string_view/contains "cpp/string/basic string view/contains") | [P1679R3](https://wg21.link/P1679R3) | 11 | 12 | 19.30\* | 13.0.0\* | | | | | [`std::to_underlying`](../utility/to_underlying "cpp/utility/to underlying") | [P1682R3](https://wg21.link/P1682R3) | 11 | 13 | 19.30\* | 13.1.6\* | | | | | Relaxing requirements for `[time\_point<>::clock](../chrono/time_point "cpp/chrono/time point")` | [P2212R2](https://wg21.link/P2212R2) | N/A | | N/A | | | | | | DR: `[std::visit()](../utility/variant/visit "cpp/utility/variant/visit")` for classes derived from `[std::variant](../utility/variant "cpp/utility/variant")` | [P2162R2](https://wg21.link/P2162R2) | 11.3 | 13 | 19.20\*\*19.30\* | 13.1.6\* | | | | | DR: Conditionally borrowed ranges | [P2017R1](https://wg21.link/P2017R1) | 11 | | 19.30\* | | | | | | DR: Repairing [input range adaptors](../ranges#Views "cpp/ranges") and `[std::counted\_iterator](../iterator/counted_iterator "cpp/iterator/counted iterator")` | [P2259R1](https://wg21.link/P2259R1) | 12 | | 19.30\*(partial)\*19.31\* | | | | | | Providing size feedback in the Allocator interface | [P0401R6](https://wg21.link/P0401R6) | | 15 | 19.30\* | | | | | | [`<spanstream>`](../header/spanstream "cpp/header/spanstream"): string-stream with [`std::span`](../container/span "cpp/container/span")-based buffer | [P0448R4](https://wg21.link/P0448R4) | 12 | | 19.31\* | | | | | | [`std::out_ptr()`](../memory/out_ptr_t/out_ptr "cpp/memory/out ptr t/out ptr"), [`std::inout_ptr()`](../memory/inout_ptr_t/inout_ptr "cpp/memory/inout ptr t/inout ptr") | [P1132R8](https://wg21.link/P1132R8) | | | 19.30\* | | | | | | `constexpr` [`type_info::operator==()`](../types/type_info/operator_cmp "cpp/types/type info/operator cmp") | [P1328R1](https://wg21.link/P1328R1) | 12 | | 19.33\* | | | | | | Iterator pair constructors for [`std::stack`](../container/stack/stack "cpp/container/stack/stack") and [`std::queue`](../container/queue/queue "cpp/container/queue/queue") | [P1425R4](https://wg21.link/P1425R4) | 12 | 14 | 19.31\* | | | | | | Non-deduction context for allocators in container deduction guides | [P1518R2](https://wg21.link/P1518R2) | 12 | 13 | 19.31\* | 13.1.6\* | | | | | [`ranges::starts_with()`](../algorithm/ranges/starts_with "cpp/algorithm/ranges/starts with") and [`ranges::ends_with()`](../algorithm/ranges/ends_with "cpp/algorithm/ranges/ends with") | [P1659R3](https://wg21.link/P1659R3) | | | 19.31\* | | | | | | Prohibiting `[std::basic\_string](../string/basic_string "cpp/string/basic string")` and `[std::basic\_string\_view](../string/basic_string_view "cpp/string/basic string view")` construction from [`nullptr`](../language/nullptr "cpp/language/nullptr") | [P2166R1](https://wg21.link/P2166R1) | 12 | 13 | 19.30\* | 13.1.6\* | | | | | [`std::invoke_r()`](../utility/functional/invoke "cpp/utility/functional/invoke") | [P2136R3](https://wg21.link/P2136R3) | 12 | | 19.31\* | | | | | | Range [constructor](../string/basic_string_view/basic_string_view "cpp/string/basic string view/basic string view") for `[std::basic\_string\_view](../string/basic_string_view "cpp/string/basic string view")` | [P1989R2](https://wg21.link/P1989R2) | 11 | 14 | 19.30\* | | | | | | Default template arguments for [`pair`](../utility/pair "cpp/utility/pair")'s forwarding [constructor](../utility/pair/pair "cpp/utility/pair/pair") | [P1951R1](https://wg21.link/P1951R1) | | 14 | 19.30\* | | | | | | Remove Garbage Collection and Reachability-Based Leak Detection ([library support](../memory#Garbage_collector_support "cpp/memory")) | [P2186R2](https://wg21.link/P2186R2) | 12 | 14 | 19.30\* | | | | | | DR: [`views::join`](../ranges/join_view "cpp/ranges/join view") should join all views of ranges | [P2328R1](https://wg21.link/P2328R1) | 11.2 | | 19.30\* | | | | | | DR: [`view`](../ranges/view "cpp/ranges/view") does not require [`default_initializable`](../concepts/default_initializable "cpp/concepts/default initializable") | [P2325R3](https://wg21.link/P2325R3) | 11.3 | | 19.30\* | | | | | | DR: Range adaptor objects bind arguments by value | [P2281R1](https://wg21.link/P2281R1) | 11 | | 19.29 (16.10)\*(partial)\*19.31\* | | | | | | DR: [`constexpr`](../language/constexpr "cpp/language/constexpr") for `[std::optional](../utility/optional "cpp/utility/optional")` and `[std::variant](../utility/variant "cpp/utility/variant")` | [P2231R1](https://wg21.link/P2231R1) | 11.3 (partial)\*12 | 13 (partial)\* | 19.31\* | 13.1.6\* (partial). | | | | | DR: [`std::format()`](../utility/format/format "cpp/utility/format/format") improvements | [P2216R3](https://wg21.link/P2216R3) | | 14 (partial)\* 15 | 19.32\* | | | | | | DR: [`views::lazy_split`](../ranges/lazy_split_view "cpp/ranges/lazy split view") and redesigned [`views::split`](../ranges/split_view "cpp/ranges/split view") | [P2210R2](https://wg21.link/P2210R2) | 12 | | 19.31\* | | | | | | zip: `views::zip`, `views::zip_transform`, `views::adjacent`, and `views::adjacent_transform` | [P2321R2](https://wg21.link/P2321R2) | 13 (partial)\* | 15 (partial)\* | 19.33\* (partial)\* | | | | | | Heterogeneous erasure overloads for associative containers | [P2077R3](https://wg21.link/P2077R3) | | | 19.32\* | | | | | | [`std::byteswap()`](../numeric/byteswap "cpp/numeric/byteswap") | [P1272R4](https://wg21.link/P1272R4) | 12 | 14 | 19.31\* | | | | | | [Printing](../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") `volatile T*` | [P1147R1](https://wg21.link/P1147R1) | 11.3 | 14 | 19.31\* | | | | | | [`basic_string::resize_and_overwrite()`](../string/basic_string/resize_and_overwrite "cpp/string/basic string/resize and overwrite") | [P1072R10](https://wg21.link/P1072R10) | 12 | 14 | 19.31\* | | | | | | Monadic operations for `[std::optional](../utility/optional "cpp/utility/optional")` | [P0798R8](https://wg21.link/P0798R8) | 12 | 14 | 19.32\* | | | | | | [`std::move_only_function`](../utility/functional/move_only_function "cpp/utility/functional/move only function") | [P0288R9](https://wg21.link/P0288R9) | 12 | | 19.32\* | | | | | | Add a conditional noexcept specification to `[std::exchange](../utility/exchange "cpp/utility/exchange")` | [P2401R0](https://wg21.link/P2401R0) | 12 | 14 | 19.25\* | | | | | | Require [`span`](../container/span "cpp/container/span") & [`basic_string_view`](../string/basic_string_view "cpp/string/basic string view") to be [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") | [P2251R1](https://wg21.link/P2251R1) | Yes | Yes | Yes | Yes | | | | | Clarifying the status of the “C headers” | [P2340R1](https://wg21.link/P2340R1) | Yes | Yes | Yes | Yes | | | | | DR: Fix `views::istream` | [P2432R1](https://wg21.link/P2432R1) | 12 | | 19.31\* | | | | | | DR: Add support for non-const-formattable types to `[std::format](../utility/format/format "cpp/utility/format/format")` | [P2418R2](https://wg21.link/P2418R2) | | 15 | 19.32\* | | | | | | DR: [`view`](../ranges/view "cpp/ranges/view") with ownership | [P2415R2](https://wg21.link/P2415R2) | 12 | 14 | 19.31\* | | | | | | DR: Fixing locale handling in chrono formatters | [P2372R3](https://wg21.link/P2372R3) | | | 19.31\* | | | | | | DR: Cleaning up integer-class types | [P2393R1](https://wg21.link/P2393R1) | | | 19.32\* | | | | | | [`<expected>`](../header/expected "cpp/header/expected") | [P0323R12](https://wg21.link/P0323R12)[P2549R1](https://wg21.link/P2549R1) | 12 | | 19.33\* | | | | | | constexpr for [`<cmath>`](../header/cmath "cpp/header/cmath") and [`<cstdlib>`](../header/cstdlib "cpp/header/cstdlib") | [P0533R9](https://wg21.link/P0533R9) | 4.6 (partial)\* | | | | | | | | [`std::unreachable()`](../utility/unreachable "cpp/utility/unreachable") | [P0627R6](https://wg21.link/P0627R6) | 12 | 15 | 19.32\* | | | | | | Deprecating `[std::aligned\_storage](../types/aligned_storage "cpp/types/aligned storage")` and `[std::aligned\_union](../types/aligned_union "cpp/types/aligned union")` | [P1413R3](https://wg21.link/P1413R3) | | | 19.33\* | | | | | | [`std::reference_constructs_from_temporary`](../types/reference_constructs_from_temporary "cpp/types/reference constructs from temporary") & [`std::reference_converts_from_temporary`](../types/reference_converts_from_temporary "cpp/types/reference converts from temporary") | [P2255R2](https://wg21.link/P2255R2) | 13 (partial)\* | | | | | | | | constexpr `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` | [P2273R3](https://wg21.link/P2273R3) | 12 | 16 (partial)\* | 19.33\* | | | | | | [`ranges::to()`](../ranges/to "cpp/ranges/to") | [P1206R7](https://wg21.link/P1206R7) | | | | | | | | | Pipe support for user-defined range adaptors | [P2387R3](https://wg21.link/P2387R3) | | | 19.34\* | | | | | | [`ranges::iota()`](../algorithm/ranges/iota "cpp/algorithm/ranges/iota"), [`ranges::shift_left()`](../algorithm/ranges/shift "cpp/algorithm/ranges/shift"), and [`ranges::shift_right()`](../algorithm/ranges/shift "cpp/algorithm/ranges/shift") | [P2440R1](https://wg21.link/P2440R1) | | | 19.34\* | | | | | | `views::join_with` | [P2441R2](https://wg21.link/P2441R2) | | | 19.34\* | | | | | | `views::chunk` and `views::slide` | [P2442R1](https://wg21.link/P2442R1) | | | 19.33\* | | | | | | `views::chunk_by` | [P2443R1](https://wg21.link/P2443R1) | | | 19.33\* | | | | | | `std::mdspan`: a non-owning multidimensional array reference | [P0009R18](https://wg21.link/P0009R18)[P2599R2](https://wg21.link/P2599R2)[P2604R0](https://wg21.link/P2604R0)[P2613R1](https://wg21.link/P2613R1) | | | | | | | | | [`<flat_map>`](../header/flat_map "cpp/header/flat map") | [P0429R9](https://wg21.link/P0429R9) | | | | | | | | | [`<flat_set>`](../header/flat_set "cpp/header/flat set") | [P1222R4](https://wg21.link/P1222R4) | | | | | | | | | [`ranges::find_last()`](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last"), [`ranges::find_last_if()`](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last"), and [`ranges::find_last_if_not()`](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last") | [P1223R5](https://wg21.link/P1223R5) | | | | | | | | | `views::stride` | [P1899R3](https://wg21.link/P1899R3) | | | 19.34\* | | | | | | Formatted output library | [P2093R14](https://wg21.link/P2093R14) | | | | | | | | | Compatibility between `[std::tuple](../utility/tuple "cpp/utility/tuple")` and tuple-like objects | [P2165R4](https://wg21.link/P2165R4) | | 2.9 (partial)\* | | Partial\* | | | | | Rectifying constant iterators, sentinels, and ranges | [P2278R4](https://wg21.link/P2278R4) | | | | | | | | | Formatting Ranges | [P2286R8](https://wg21.link/P2286R8) | | | | | | | | | `constexpr` for integral overloads of [`std::to_chars()`](../utility/to_chars "cpp/utility/to chars") and [`std::from_chars()`](../utility/from_chars "cpp/utility/from chars"). | [P2291R3](https://wg21.link/P2291R3) | | | 19.34\* | | | | | | [`ranges::contains()`](../algorithm/ranges/contains "cpp/algorithm/ranges/contains") and [`ranges::contains_subrange()`](../algorithm/ranges/contains "cpp/algorithm/ranges/contains") | [P2302R4](https://wg21.link/P2302R4) | | | 19.34\* | | | | | | Ranges fold algorithms | [P2322R6](https://wg21.link/P2322R6) | | | | | | | | | `views::cartesian_product` | [P2374R4](https://wg21.link/P2374R4)[P2540R1](https://wg21.link/P2540R1) | | | | | | | | | Adding move-only types support for comparison concepts | [P2404R3](https://wg21.link/P2404R3) | | | | | | | | | Ranges iterators as inputs to non-ranges algorithms | [P2408R5](https://wg21.link/P2408R5) | | | 19.34\* | | | | | | constexpr `[std::bitset](../utility/bitset "cpp/utility/bitset")` | [P2417R2](https://wg21.link/P2417R2) | | 16 | 19.34\* | | | | | | [`basic_string::substr()`](../string/basic_string/substr "cpp/string/basic string/substr") `&&` | [P2438R2](https://wg21.link/P2438R2) | | | 19.34\* | | | | | | `views::as_rvalue` | [P2446R2](https://wg21.link/P2446R2) | | | 19.34\* | | | | | | Standard Library Modules | [P2465R3](https://wg21.link/P2465R3) | | | | | | | | | [`std::forward_like()`](../utility/forward_like "cpp/utility/forward like") | [P2445R1](https://wg21.link/P2445R1) | | 16 | 19.34\* | | | | | | Support exclusive mode for `[std::fstream](../io/basic_fstream "cpp/io/basic fstream")` | [P2467R1](https://wg21.link/P2467R1) | 12 | | | | | | | | `views::repeat` | [P2474R2](https://wg21.link/P2474R2) | | | | | | | | | Relaxing range adaptors to allow for move-only types | [P2494R2](https://wg21.link/P2494R2) | | | 19.34\* | | | | | | `[std::basic\_string\_view](../string/basic_string_view "cpp/string/basic string view")` range [constructor](../string/basic_string_view/basic_string_view "cpp/string/basic string view/basic string view") should be explicit | [P2499R0](https://wg21.link/P2499R0) | 12.2 | 16 | 19.34\* | | | | | | `std::generator`: synchronous coroutine generator for ranges | [P2502R2](https://wg21.link/P2502R2) | | | | | | | | | `std::basic_format_string` | [P2508R1](https://wg21.link/P2508R1) | | 15 | | | | | | | Add a conditional noexcept specification to `[std::apply](../utility/apply "cpp/utility/apply")` | [P2517R0](https://wg21.link/P2517R0) | 10 | | 19.34\* | | | | | | Improve default container formatting | [P2585R1](https://wg21.link/P2585R1) | | | | | | | | | Explicit lifetime management | [P2590R2](https://wg21.link/P2590R2) | | | | | | | | | Clarify handling of encodings in localized formatting of chrono types | [P2419R2](https://wg21.link/P2419R2) | | | 19.34\*\* | | | | | | `[std::move\_iterator](../iterator/move_iterator "cpp/iterator/move iterator")` should not always be [`input_iterator`](../iterator/input_iterator "cpp/iterator/input iterator") | [P2520R0](https://wg21.link/P2520R0) | | | 19.34\*\* | | | | | | Deduction guides update for [deducing `this`](../language/member_functions#Explicit_object_parameter "cpp/language/member functions") | [LWG3617](https://cplusplus.github.io/LWG/issue3617) | | | 19.34\* | | | | | | Deduction guides update for `static operator()` | [P1169R4](https://wg21.link/P1169R4) | | | | | | | | | Standard names and library support for extended floating-point types | [P1467R9](https://wg21.link/P1467R9) | | | | | | | | | C++23 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library |
programming_docs
cpp Compiler support for C++14 Compiler support for C++14 ========================== ### C++14 core language features | C++14 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Tweaked wording for [contextual conversions](../language/implicit_conversion#Contextual_conversions "cpp/language/implicit conversion") | [N3323](https://wg21.link/N3323) | 4.9 | 3.4 | 18.0\* | Yes | 4.9 | 16.0 | 13.1.2\* | 5.15 | 10.3 | 8.6 | 16.1 | 9.0 | | [Binary literals](../language/integer_literal "cpp/language/integer literal") | [N3472](https://wg21.link/N3472) | 4.3 (GNU)4.9 | 2.9 | 19.0 (2015)\* | Yes | 4.10 | 11.0 | 13.1.2\* | 5.14 | 10.3 | 8.6 | 2015 | 9.0 | | [`decltype(auto)`](../language/auto "cpp/language/auto"), Return type deduction for normal functions | [N3638](https://wg21.link/N3638) | 4.8 (partial)\*4.9 | 3.3 (partial)\*3.4 | 19.0 (2015)\* | Yes | 4.9 | 15.0 | 13.1.2\* | 5.15 | 10.3 | 8.6 | 16.1 | 9.0 | | Initialized/Generalized lambda captures (init-capture) | [N3648](https://wg21.link/N3648) | 4.5 (partial)4.9 | 3.4 | 19.0 (2015)\* | Yes | 4.10 | 15.0 | 16.1.1\* | 5.15 | 10.3 | 8.6 | 16.1 | 9.0 | | [Generic lambda expressions](../language/lambda#Explanation "cpp/language/lambda") | [N3649](https://wg21.link/N3649) | 4.9 | 3.4 | 19.0 (2015)\* | Yes | 4.10 | 16.0 | 13.1.2\* | 5.15 | 10.3 | 8.6 | 16.1 | 9.0 | | [Variable templates](../language/variable_template "cpp/language/variable template") | [N3651](https://wg21.link/N3651) | 5 | 3.4 | 19.0 (Update 2)\* | Yes | 4.11 | 17.0 | 13.1.2\* | 5.15 | 10.3 | 8.6 | 17.4 | 9.0 | | Extended constexpr | [N3652](https://wg21.link/N3652) | 5 | 3.4 | 19.10\* | Yes | 4.11 | 17.0 | 13.1.2\* | 5.15 | 10.3 | 8.6 | 17.4 | 9.0 | | Aggregates with [default member initializers](../language/data_members#Member_initialization "cpp/language/data members") | [N3653](https://wg21.link/N3653) | 5 | 3.3 | 19.10\* | Yes | 4.9 | 16.0 | 16.1.1\* | 5.14 | 10.3 | 8.6 | 16.1 | 9.0 | | Omitting/extending [memory allocations](../language/new#Allocation "cpp/language/new") | [N3664](https://wg21.link/N3664) | N/A | 3.4 | N/A | Yes | N/A | N/A | N/A | N/A | 10.3 | 8.6 | 17.4 | N/A | | `[[[deprecated](../language/attributes/deprecated "cpp/language/attributes/deprecated")]]` attribute | [N3760](https://wg21.link/N3760) | 4.9 | 3.4 | 19.0 (2015)\* | Yes | 4.9 | 15.0\*16.0 | 13.1.2\* | 5.14 | 10.3 | 8.6 | 16.1 | 9.0 | | [Sized deallocation](../language/delete "cpp/language/delete") | [N3778](https://wg21.link/N3778) | 5 | 3.4 | 19.0 (2015)\* | Yes | 4.10.1 | 17.0 | 16.1.1\* | 5.14 | 10.3 | 8.6 | 16.1 | | | [Single quote as digit separator](../language/integer_literal#Single_quote "cpp/language/integer literal") | [N3781](https://wg21.link/N3781) | 4.9 | 3.4 | 19.0 (2015)\* | Yes | 4.10 | 16.0 | 13.1.2\* | 5.14 | 10.3 | 8.6 | 2015 | 9.0 | | C++14 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc | ### C++14 library features | C++14 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constexpr` for [`<complex>`](../header/complex "cpp/header/complex") | [N3302](https://wg21.link/N3302) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | Transparent [operator functors](../utility/functional#Operator_function_objects "cpp/utility/functional") | [N3421](https://wg21.link/N3421) | 4.9 | 3.4 | 18.0\* | Yes | 5.15 | 10.3 | 8.6 | | `[std::result\_of](../types/result_of "cpp/types/result of")` and [SFINAE](../language/sfinae "cpp/language/sfinae") | [N3462](https://wg21.link/N3462) | 5 | Yes | 19.0 (Update 2)\* | Yes | 5.15 | 10.3 | 8.6 | | `constexpr` for [`<chrono>`](../header/chrono "cpp/header/chrono") | [N3469](https://wg21.link/N3469) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `constexpr` for [`<array>`](../header/array "cpp/header/array") | [N3470](https://wg21.link/N3470) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `constexpr` for [`<initializer_list>`](../header/initializer_list "cpp/header/initializer list"), [`<utility>`](../header/utility "cpp/header/utility") and [`<tuple>`](../header/tuple "cpp/header/tuple") | [N3471](https://wg21.link/N3471) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | Improved `[std::integral\_constant](../types/integral_constant "cpp/types/integral constant")` | [N3545](https://wg21.link/N3545) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | [User-defined literals](../language/user_literal#Standard_library "cpp/language/user literal") for [`<chrono>`](../header/chrono "cpp/header/chrono") and [`<string>`](../header/string "cpp/header/string") | [N3642](https://wg21.link/N3642) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | [Null forward iterators](../named_req/forwarditerator#Singular_iterators "cpp/named req/ForwardIterator") | [N3644](https://wg21.link/N3644) | 5 (partial) 10 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `[std::quoted](../io/manip/quoted "cpp/io/manip/quoted")` | [N3654](https://wg21.link/N3654) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `[std::make\_unique](../memory/unique_ptr/make_unique "cpp/memory/unique ptr/make unique")` | [N3656](https://wg21.link/N3656) | 4.9 | 3.4 | 18.0\* | Yes | 5.15 | 10.3 | 8.6 | | Heterogeneous associative lookup | [N3657](https://wg21.link/N3657) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `[std::integer\_sequence](../utility/integer_sequence "cpp/utility/integer sequence")` | [N3658](https://wg21.link/N3658) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `[std::shared\_timed\_mutex](../thread/shared_timed_mutex "cpp/thread/shared timed mutex")` | [N3659](https://wg21.link/N3659) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | `[std::exchange](../utility/exchange "cpp/utility/exchange")` | [N3668](https://wg21.link/N3668) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | fixing `constexpr` member functions without `const` | [N3669](https://wg21.link/N3669) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | [`std::get<T>()`](../utility/pair/get "cpp/utility/pair/get") | [N3670](https://wg21.link/N3670) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | Dual-Range `[std::equal](../algorithm/equal "cpp/algorithm/equal")`, `[std::is\_permutation](../algorithm/is_permutation "cpp/algorithm/is permutation")`, `[std::mismatch](../algorithm/mismatch "cpp/algorithm/mismatch")` | [N3671](https://wg21.link/N3671) | 5 | 3.4 | 19.0 (2015)\* | Yes | 5.15 | 10.3 | 8.6 | | C++14 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | cpp Compiler support for C++11 Compiler support for C++11 ========================== ### C++11 core language features | C++11 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc | HP aCC | Digital Mars C++ | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | C99 [preprocessor](../preprocessor "cpp/preprocessor") | [N1653](https://wg21.link/N1653) | 4.3 | Yes | 19.0 (2015)\* (partial)\*19.26\* | Yes | 4.1 | 11.1 | 10.1 | 5.9 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | Yes | | [`static_assert`](../language/static_assert "cpp/language/static assert") | [N1720](https://wg21.link/N1720) | 4.3 | 2.9 | 16.0\* | Yes | 4.1 | 11.0 | 11.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | 8.52 | | Right angle brackets | [N1757](https://wg21.link/N1757) | 4.3 | Yes | 14.0\* | Yes | 4.1 | 11.0 | 12.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | | | | Extended [`friend` declarations](../language/friend "cpp/language/friend") | [N1791](https://wg21.link/N1791) | 4.7 | 2.9 | 16.0\* (partial)18.0\* | Yes | 4.1 | 11.1\*12.0 | 11.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [`long long`](../language/types#long_long "cpp/language/types") | [N1811](https://wg21.link/N1811) | Yes | Yes | 14.0\* | Yes | Yes | Yes | Yes | Yes | Yes | 8.4 | 2015 | 7.0 | Yes | Yes | | Compiler support for [type traits](../meta#Type_traits "cpp/meta") | [N1836](https://wg21.link/N1836)[N2518](https://wg21.link/N2518)\*[N2984](https://wg21.link/N2984)[N3142](https://wg21.link/N3142) | 4.3\*4.8\*5 | 3.0 | 14.0\*(partial)\*19.0 (2015)\* | Yes | 4.0 | 10.0 | 13.1.3 | 5.13 | Yes | 8.4 | 2015 | | 6.16 | | | [`auto`](../language/auto "cpp/language/auto") | [N1984](https://wg21.link/N1984) | 4.4 | Yes | 16.0\* | Yes | 3.9 | 11.0 (v0.9)12.0 | 11.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [Delegating constructors](../language/initializer_list#Delegating_constructor "cpp/language/initializer list") | [N1986](https://wg21.link/N1986) | 4.7 | 3.0 | 18.0\* | Yes | 4.7 | 14.0 | 11.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | `extern template` | [N1987](https://wg21.link/N1987) | 3.3 | Yes | 12.0\* | Yes | 3.9 | 9.0 | 11.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [`constexpr`](../language/constexpr "cpp/language/constexpr") | [N2235](https://wg21.link/N2235) | 4.6 | 3.1 | 19.0 (2015)\* | Yes | 4.6 | 13.0\*14.0 | 12.1\*13.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | [Template aliases](../language/type_alias "cpp/language/type alias") | [N2258](https://wg21.link/N2258) | 4.7 | 3.0 | 18.0\* | Yes | 4.2 | 12.1 | 13.1.1\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | | | [`char16_t`](../language/types#char16_t "cpp/language/types") and [`char32_t`](../language/types#char32_t "cpp/language/types") | [N2249](https://wg21.link/N2249) | 4.4 | 2.9 | 19.0 (2015)\* | Yes | 4.4 | 12.1\*14.0 | 13.1.1\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | 8.52 | | [`alignas`](../language/alignas "cpp/language/alignas") | [N2341](https://wg21.link/N2341) | 4.8 | 3.0 | 19.0 (2015)\* | Yes | 4.8 | 15.0 | 13.1.2\* | 5.13 | Yes | 8.6 | 2015 | 7.0 | | | | [`alignof`](../language/alignof "cpp/language/alignof") | [N2341](https://wg21.link/N2341) | 4.5 | 2.9 | 19.0 (2015)\* | Yes | 4.8 | 15.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | | | | Defaulted and deleted functions | [N2346](https://wg21.link/N2346) | 4.4 | 3.0 | 18.0\* | Yes | 4.1 | 12.0 | 13.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [Strongly-typed `enum`](../language/enum#Scoped_enumerations "cpp/language/enum") | [N2347](https://wg21.link/N2347) | 4.4 | 2.9 | 17.0\* | Yes | 4.0 | 13.0 | 12.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [Atomic operations](../thread#Atomic_operations "cpp/thread") | [N2427](https://wg21.link/N2427) | 4.4 | 3.1 | 17.0\* | Yes | Yes | 13.0 | 13.1.2\* | 5.14 | Yes | 8.4 | 2015 | | | | | [`nullptr`](../language/nullptr "cpp/language/nullptr") | [N2431](https://wg21.link/N2431) | 4.6 | 2.9 | 16.0\* | Yes | 4.2 | 12.1 | 13.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | 8.52 | | Explicit [conversion operators](../language/cast_operator "cpp/language/cast operator") | [N2437](https://wg21.link/N2437) | 4.5 | 3.0 | 18.0\* | Yes | 4.4 | 13.0 | 12.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | | | ref-qualifiers | [N2439](https://wg21.link/N2439) | 4.8.1 | 2.9 | 19.0 (2015)\* | Yes | 4.7 | 14.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | Unicode [string literals](../language/string_literal "cpp/language/string literal") | [N2442](https://wg21.link/N2442) | 4.4 | 3.0 | 19.0 (2015)\* | Yes | 4.7 | 11.0\* | 10.1\*13.1.1\* | 5.7 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | 8.52 | | Raw [string literals](../language/string_literal "cpp/language/string literal") | [N2442](https://wg21.link/N2442) | 4.5 | Yes | 18.0\* | Yes | 4.7 | 14.0 | 13.1.1\*, except AIX xlC 13.1.3 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | 8.52 | | [Inline namespaces](../language/namespace#Inline_namespaces "cpp/language/namespace") | [N2535](https://wg21.link/N2535) | 4.4 | 2.9 | 19.0 (2015)\* | Yes | 4.5 | 14.0 | 11.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | [Inheriting constructors](../language/using_declaration#Inheriting_constructors "cpp/language/using declaration") | [N2540](https://wg21.link/N2540) | 4.8 | 3.3 | 19.0 (2015)\* | Yes | 4.8 | 15.0 | 13.1.1\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | | | | [Trailing function return types](../language/function#Function_declaration "cpp/language/function") | [N2541](https://wg21.link/N2541) | 4.4 | 2.9 | 16.0\* | Yes | 4.1 | 12.0 | 12.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | | | Unrestricted [unions](../language/union "cpp/language/union") | [N2544](https://wg21.link/N2544) | 4.6 | 3.0 | 19.0 (2015)\* | Yes | 4.6 | 14.0\* | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | [Variadic templates](../language/parameter_pack "cpp/language/parameter pack") | [N2242](https://wg21.link/N2242)[N2555](https://wg21.link/N2555) | 4.3 (N2242)4.4 | 2.9 | 18.0\* | Yes | 4.3 (N2242)4.3 | 12.1 | 11.1 (N2242) | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | | | [Expression SFINAE](../language/sfinae#Expression_SFINAE "cpp/language/sfinae") | [N2634](https://wg21.link/N2634) | 4.4 | 2.9 | 19.14\* | Yes | 4.2 | 12.1 | | | Yes | 8.4 | 2015 | 7.0 | | | | Local and unnamed types as template parameters | [N2657](https://wg21.link/N2657) | 4.5 | 2.9 | 16.0\* | Yes | 4.2 | 12.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | | | [Thread-local storage](../language/storage_duration "cpp/language/storage duration") | [N2659](https://wg21.link/N2659) | 4.4 (partial)4.8 | 3.3\* | 16.0\* (partial)19.0 (2015)\* | Yes | 4.8 | 11.1 (partial)15.0\* | 10.1 (partial)\*13.1.2 (partial)\* | 5.9 (partial) | Yes | 8.4 | 2015 | | | 8.52 (partial) | | Dynamic initialization and destruction with concurrency ([magic statics](../language/storage_duration#Static_local_variables "cpp/language/storage duration")) | [N2660](https://wg21.link/N2660) | 4.3 | 2.9 | 19.0 (2015)\* | Yes | Yes | 11.1\* | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | | A.06.25 | | | Garbage Collection and Reachability-Based Leak Detection | [N2670](https://wg21.link/N2670) | | | | | | | | | | | | | | | | [Initializer lists](../language/list_initialization "cpp/language/list initialization") | [N2672](https://wg21.link/N2672) | 4.4 | 3.1 | 18.0\* | Yes | 4.5 | 13.0 (partial)14.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | [Non-static data member initializers](../language/data_members#Member_initialization "cpp/language/data members") | [N2756](https://wg21.link/N2756) | 4.7 | 3.0 | 18.0\* | Yes | 4.6 | 14.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | [Attributes](../language/attributes "cpp/language/attributes") | [N2761](https://wg21.link/N2761) | 4.8 | 3.3 | 19.0 (2015)\* | Yes | 4.2 | 12.1 | 13.1.1\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.27 | | | [Forward (opaque) `enum` declarations](../language/enum "cpp/language/enum") | [N2764](https://wg21.link/N2764) | 4.6 | 3.1 | 17.0\* | Yes | 4.5 | 11.1 (partial)14.0 | 12.1 | 5.13 | Yes | 8.4 | 2015 | 7.0 | | | | [User-defined literals](../language/user_literal "cpp/language/user literal") | [N2765](https://wg21.link/N2765) | 4.7 | 3.1 | 19.0 (2015)\* | Yes | 4.8 | 15.0 | 13.1.2\* | 5.14 | Yes | 8.4 | 2015 | 7.0 | | | | [Rvalue references](../language/reference#Rvalue_references "cpp/language/reference") | [N2118](https://wg21.link/N2118)[N2844](https://wg21.link/N2844)[CWG1138](https://cplusplus.github.io/CWG/issues/1138.html) | 4.3 (N2118)4.5 | 2.9 | 16.0\* (N2844)17.0\* | Yes | 4.5 | 11.1 (N2118)12.0 (N2844)14.0 | 12.1 | 5.13 | Yes | 8.4 | 2015 | 7.0\* | A.06.25 | | | [Lambda expressions](../language/lambda "cpp/language/lambda") | [N2550](https://wg21.link/N2550)[N2658](https://wg21.link/N2658)[N2927](https://wg21.link/N2927) | 4.5 | 3.1 | 16.0\* (N2658)17.0\* | Yes | 4.1 | 12.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [Range-for loop](../language/range-for "cpp/language/range-for") | [N2930](https://wg21.link/N2930)[N3271](https://wg21.link/N3271) | 4.6 | 3.0 | 17.0\* | Yes | 4.5 | 13.0 | 13.1.2\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | [`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") | [N3050](https://wg21.link/N3050) | 4.6 | 3.0 | 19.0 (2015)\* | Yes | 4.5 | 14.0 | 13.1.1\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.28 | | | Defaulted move [special](../language/member_functions#Special_member_functions "cpp/language/member functions") [member](../language/move_constructor "cpp/language/move constructor") [functions](../language/move_assignment "cpp/language/move assignment") | [N3053](https://wg21.link/N3053) | 4.6 | 3.0 | 19.0 (2015)\* | Yes | 4.5 | 14.0 | | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | | | [`override`](../language/override "cpp/language/override") and [`final`](../language/final "cpp/language/final") | [N2928](https://wg21.link/N2928)[N3206](https://wg21.link/N3206)[N3272](https://wg21.link/N3272) | 4.7 | 2.9 | 14.0\* (partial)17.0\* | Yes | 4.8 | 12.0 (N2928)14.0 | 13.1.1\* | 5.13 | Yes | 8.4 | 2015 | 7.0 | | | | [`decltype`](../language/decltype "cpp/language/decltype") | [N2343](https://wg21.link/N2343)[N3276](https://wg21.link/N3276) | 4.3 (N2343)4.8.1 | 2.9 | 16.0\* | Yes | 4.2 (N2343)4.8 | 11.0 (N2343)12.0 | 11.1 (N2343) | 5.13 | Yes | 8.4 | 2015 | 7.0 | A.06.25 | 8.52 (N2343) | | C++11 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc | HP aCC | Digital Mars C++ | ### C++11 library features | C++11 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | [Type traits](../meta#Type_traits "cpp/meta") | [N1836](https://wg21.link/N1836)[N2240](https://wg21.link/N2240)[N2244](https://wg21.link/N2244)[N2255](https://wg21.link/N2255)[N2342](https://wg21.link/N2342)[N2984](https://wg21.link/N2984)[N3142](https://wg21.link/N3142) | 4.3\*4.8\*5 | 3.0 | 14.0\*(partial)\*19.0 (2015)\* | Yes | 5.13 | Yes | 8.4 | | [Garbage Collection](../header/memory#Functions "cpp/header/memory") and Reachability-Based Leak Detection ([library support](../memory#Garbage_collector_support "cpp/memory")) | [N2670](https://wg21.link/N2670) | 6(no-op) | 3.4(no-op) | 19.0 (2015)\*(no-op) | Yes(no-op) | | | | | [Money, Time, and hexfloat I/O manipulators](../io/manip "cpp/io/manip") | [N2071](https://wg21.link/N2071)[N2072](https://wg21.link/N2072) | 5 | 3.8 | 19.0 (2015)\* | Yes | 5.15 | | | | Disallowing [COW (copy-on-write)](../language/acronyms "cpp/language/acronyms") `[string](../string/basic_string "cpp/string/basic string")` | [N2668](https://wg21.link/N2668) | 5 | Yes | Yes | Yes | Yes | | | | [Regular expressions library](../regex "cpp/regex") | [N1429](https://wg21.link/N1429) | 4.9 | ? | ? | | | | | | C++11 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library |
programming_docs
cpp Compiler support for C++17 Compiler support for C++17 ========================== ### C++17 core language features | C++17 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | DR: New `auto` rules for direct-list-initialization | [N3922](https://wg21.link/N3922) | 5 | 3.8 | 19.0 (2015)\* | Yes | 4.10.1 | 17.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | [`static_assert`](../language/static_assert "cpp/language/static assert") with no message | [N3928](https://wg21.link/N3928) | 6 | 2.5 | 19.10\* | Yes | 4.12 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | `typename` in a template template parameter | [N4051](https://wg21.link/N4051) | 5 | 3.5 | 19.0 (2015)\* | Yes | 4.10.1 | 17.0 | | | 10.3 | 11.0 | 17.7 | Yes\* | | Removing [trigraphs](../language/operator_alternative#Trigraphs_.28removed_in_C.2B.2B17.29 "cpp/language/operator alternative") | [N4086](https://wg21.link/N4086) | 5 | 3.5 | 16.0\* | Yes | 5.0 | | | | 10.3 | 11.0 | 19.1 | 11.0 | | [Nested namespace](../language/namespace#Syntax "cpp/language/namespace") definition | [N4230](https://wg21.link/N4230) | 6 | 3.6 | 19.0 (Update 3)\* | Yes | 4.12 | 17.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | [Attributes](../language/attributes "cpp/language/attributes") for namespaces and enumerators | [N4266](https://wg21.link/N4266) | 4.9 (partial)\*6 | 3.6 | 19.0 (2015)\* | Yes | 4.11 | 17.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | [`u8` character literals](../language/character_literal "cpp/language/character literal") | [N4267](https://wg21.link/N4267) | 6 | 3.6 | 19.0 (2015)\* | Yes | 4.11 | 17.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | Allow constant evaluation for all non-type template arguments | [N4268](https://wg21.link/N4268) | 6 | 3.6 | 19.12\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | [Fold Expressions](../language/fold "cpp/language/fold") | [N4295](https://wg21.link/N4295) | 6 | 3.6 | 19.12\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 18.1 | 11.0 | | [Unary fold expressions](../language/fold#Explanation "cpp/language/fold") and empty parameter packs | [P0036R0](https://wg21.link/P0036R0) | 6 | 3.9 | 19.12\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 19.1 | 11.0 | | Remove Deprecated Use of the [`register`](../keyword/register "cpp/keyword/register") Keyword | [P0001R1](https://wg21.link/P0001R1) | 7 | 3.8 | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | Remove Deprecated `operator++(bool)` | [P0002R1](https://wg21.link/P0002R1) | 7 | 3.8 | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | Make exception specifications part of the type system | [P0012R1](https://wg21.link/P0012R1) | 7 | 4 | 19.12\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 19.1 | 11.0 | | [Aggregate classes](../language/aggregate_initialization "cpp/language/aggregate initialization") with base classes | [P0017R1](https://wg21.link/P0017R1) | 7 | 3.9 | 19.14\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | [`__has_include`](../preprocessor/include "cpp/preprocessor/include") in preprocessor conditionals | [P0061R1](https://wg21.link/P0061R1) | 5 | Yes | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | DR: New specification for [inheriting constructors](../language/using_declaration#Inheriting_constructors "cpp/language/using declaration") (DR1941 et al) | [P0136R1](https://wg21.link/P0136R1) | 7 | 3.9 | 19.14\* | Yes | 6.1 | | | | 10.3 | 11.0 | 19.1 | 11.0 | | Lambda capture of `*this` | [P0018R3](https://wg21.link/P0018R3) | 7 | 3.9 | 19.11\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 18.1 | 11.0 | | Direct-list-initialization of enumerations | [P0138R2](https://wg21.link/P0138R2) | 7 | 3.9 | 19.11\* | Yes | 4.14 | 18.0 | | | 10.3 | 11.0 | 19.1 | 11.0 | | [constexpr lambda expressions](../language/lambda "cpp/language/lambda") | [P0170R1](https://wg21.link/P0170R1) | 7 | 5 | 19.11\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 18.1 | 11.0 | | Differing begin and end types in [range-based for](../language/range-for "cpp/language/range-for") | [P0184R0](https://wg21.link/P0184R0) | 6 | 3.9 | 19.10\* | Yes | 4.12 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | `[[[fallthrough](../language/attributes/fallthrough "cpp/language/attributes/fallthrough")]]` [attribute](../language/attributes "cpp/language/attributes") | [P0188R1](https://wg21.link/P0188R1) | 7 | 3.9 | 19.10\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | `[[[nodiscard](../language/attributes/nodiscard "cpp/language/attributes/nodiscard")]]` [attribute](../language/attributes "cpp/language/attributes") | [P0189R1](https://wg21.link/P0189R1) | 7 | 3.9 | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | `[[[maybe\_unused](../language/attributes/maybe_unused "cpp/language/attributes/maybe unused")]]` [attribute](../language/attributes "cpp/language/attributes") | [P0212R1](https://wg21.link/P0212R1) | 7 | 3.9 | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | Hexadecimal [floating-point literals](../language/floating_literal "cpp/language/floating literal") | [P0245R1](https://wg21.link/P0245R1) | 3.0 | Yes | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | Using attribute namespaces without repetition | [P0028R4](https://wg21.link/P0028R4) | 7 | 3.9 | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | [Dynamic memory allocation](../language/new "cpp/language/new") for over-aligned data | [P0035R4](https://wg21.link/P0035R4) | 7 | 4 | 19.12\* | 10.0.0\* | 4.14 | 19.0 | | | 10.3 | 11.0 | 19.1 | 11.0 | | [Class template argument deduction](../language/class_template_argument_deduction "cpp/language/class template argument deduction") | [P0091R3](https://wg21.link/P0091R3) | 7 | 5 | 19.14\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | Non-type template parameters with `auto` type | [P0127R2](https://wg21.link/P0127R2) | 7 | 4 | 19.14\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | Guaranteed [copy elision](../language/copy_elision "cpp/language/copy elision") | [P0135R1](https://wg21.link/P0135R1) | 7 | 4 | 19.13\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | Replacement of class objects containing reference members | [P0137R1](https://wg21.link/P0137R1) | 7 | 6 | 19.14\* | Yes | 5.0 | | | | 10.3 | 11.0 | 19.1 | 11.0 | | Stricter [expression evaluation order](../language/eval_order "cpp/language/eval order") | [P0145R3](https://wg21.link/P0145R3) | 7 | 4 | 19.14\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | [Structured Bindings](../language/structured_binding "cpp/language/structured binding") | [P0217R3](https://wg21.link/P0217R3) | 7 | 4 | 19.11\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 18.1 | 11.0\* | | Ignore unknown [attributes](../language/attributes "cpp/language/attributes") | [P0283R2](https://wg21.link/P0283R2) | Yes | 3.9 | 19.11\* | Yes | 4.13 | 18.0 | | | 10.3 | 11.0 | 17.7 | 11.0 | | [constexpr if](../language/if "cpp/language/if") statements | [P0292R2](https://wg21.link/P0292R2) | 7 | 3.9 | 19.11\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 18.1 | 11.0 | | init-statements for [if](../language/if "cpp/language/if") and [switch](../language/switch "cpp/language/switch") | [P0305R1](https://wg21.link/P0305R1) | 7 | 3.9 | 19.11\* | Yes | 4.14 | 18.0 | | | 10.3 | 11.0 | 18.1 | 11.0 | | [Inline variables](../language/inline "cpp/language/inline") | [P0386R2](https://wg21.link/P0386R2) | 7 | 3.9 | 19.12\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 18.1 | 11.0 | | Removing [dynamic exception specifications](../language/except_spec "cpp/language/except spec") | [P0003R5](https://wg21.link/P0003R5) | 7 | 4 | 19.10\* | Yes | 4.14 | 19.0 | | | 10.3 | 11.0 | 19.1 | 11.0 | | Pack expansions in using-declarations | [P0195R2](https://wg21.link/P0195R2) | 7 | 4 | 19.14\* | Yes | 5.0 | 19.0 | | | 10.3 | 11.0 | 19.1 | 11.0 | | DR: Matching of template template-arguments excludes compatible templates | [P0522R0](https://wg21.link/P0522R0) | 7 | 4 | 19.12\* | Yes | 5.0 | 19.0.1 | | | 10.3 | 11.0 | 19.1 | 11.0 | | C++17 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc | ### C++17 library features | C++17 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Intel Parallel STL | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `[std::void\_t](../types/void_t "cpp/types/void t")` | [N3911](https://wg21.link/N3911) | 6 | 3.6 | 19.0 (2015)\* | Yes | N/A | | 10.3 | | | [`std::uncaught_exceptions()`](../error/uncaught_exception "cpp/error/uncaught exception") | [N4259](https://wg21.link/N4259) | 6 | 3.7 | 19.0 (2015)\* | Yes | N/A | | 10.3 | | | `[std::size()](../iterator/size "cpp/iterator/size")`, `[std::empty()](../iterator/empty "cpp/iterator/empty")` and `[std::data()](../iterator/data "cpp/iterator/data")` | [N4280](https://wg21.link/N4280) | 6 | 3.6 | 19.0 (2015)\* | Yes | N/A | | 10.3 | | | Improving `[std::pair](../utility/pair "cpp/utility/pair")` and `[std::tuple](../utility/tuple "cpp/utility/tuple")` | [N4387](https://wg21.link/N4387) | 6 | 4 | 19.0 (Update 2)\* | Yes | N/A | | 10.3 | | | `[std::bool\_constant](../types/integral_constant "cpp/types/integral constant")` | [N4389](https://wg21.link/N4389) | 6 | 3.7 | 19.0 (2015)\* | Yes | N/A | | 10.3 | | | `[std::shared\_mutex](../thread/shared_mutex "cpp/thread/shared mutex")` (untimed) | [N4508](https://wg21.link/N4508) | 6 | 3.7 | 19.0 (Update 2)\* | Yes | N/A | | 10.3 | | | [Type traits](../meta "cpp/meta") variable templates | [P0006R0](https://wg21.link/P0006R0) | 7 | 3.8 | 19.0 (Update 2)\* | Yes | N/A | | 10.3 | | | [Logical operator type traits](../meta#Operations_on_traits "cpp/meta") | [P0013R1](https://wg21.link/P0013R1) | 6 | 3.8 | 19.0 (Update 2)\* | Yes | N/A | | 10.3 | | | Parallel algorithms and execution policies | [P0024R2](https://wg21.link/P0024R2) | 9\* | | 19.14\* | | 18.0\* | | | | | `[std::clamp()](../algorithm/clamp "cpp/algorithm/clamp")` | [P0025R0](https://wg21.link/P0025R0) | 7 | 3.9 | 19.0 (Update 3)\* | 10.0.0\* | N/A | | 10.3 | | | [Hardware interference size](../thread/hardware_destructive_interference_size "cpp/thread/hardware destructive interference size") | [P0154R1](https://wg21.link/P0154R1) | 12 | 15 (partial)\* | 19.11\* | | N/A | | 10.3 | | | [(nothrow-)swappable traits](../types/is_swappable "cpp/types/is swappable") | [P0185R1](https://wg21.link/P0185R1) | 7 | 3.9 | 19.0 (Update 3)\* | 10.0.0\* | N/A | | 10.3 | | | [File system library](../filesystem "cpp/filesystem") | [P0218R1](https://wg21.link/P0218R1) | 8 | 7 | 19.14\* | 11.0.0\* | N/A | | 10.3 | | | `[std::string\_view](../string/basic_string_view "cpp/string/basic string view")` | [N3921](https://wg21.link/N3921)[P0220R1](https://wg21.link/P0220R1) | 7 | 4 | 19.10\* | 10.0.0\* | N/A | | 10.3 | | | `[std::any](../utility/any "cpp/utility/any")` | [P0220R1](https://wg21.link/P0220R1) | 7 | 4 | 19.10\* | 10.0.0\* | N/A | | 10.3 | | | `[std::optional](../utility/optional "cpp/utility/optional")` | [P0220R1](https://wg21.link/P0220R1) | 7 | 4 | 19.10\* | 10.0.0\* | N/A | | 10.3 | | | [Polymorphic memory resources](../header/memory_resource "cpp/header/memory resource") | [P0220R1](https://wg21.link/P0220R1) | 9 | | 19.13\* | | N/A | | 10.3 | | | [Mathematical special functions](../numeric/special_functions "cpp/numeric/special functions") | [P0226R1](https://wg21.link/P0226R1) | 7 | | 19.14\* | | N/A | | 10.3 | | | Major portion of C11 standard library | [P0063R3](https://wg21.link/P0063R3) | 9 | 7 | 19.0 (2015)\*(partial)\* | 10.0.0\* | N/A | | | | | Splicing [`Maps`](../container/map/merge "cpp/container/map/merge") and [`Sets`](../container/set/merge "cpp/container/set/merge") | [P0083R3](https://wg21.link/P0083R3) | 7 | 8 | 19.12\* | 10.0.0\* | N/A | | | | | `[std::variant](../utility/variant "cpp/utility/variant")` | [P0088R3](https://wg21.link/P0088R3) | 7 | 4 | 19.10\* | 10.0.0\* | N/A | | 10.3 | | | `[std::make\_from\_tuple()](../utility/make_from_tuple "cpp/utility/make from tuple")` | [P0209R2](https://wg21.link/P0209R2) | 7 | 3.9 | 19.10\* | Yes | N/A | | 10.3 | | | `[std::has\_unique\_object\_representations](../types/has_unique_object_representations "cpp/types/has unique object representations")` | [P0258R2](https://wg21.link/P0258R2) | 7 | 6 | 19.11\* | Yes | N/A | | 10.3 | | | `[std::gcd()](../numeric/gcd "cpp/numeric/gcd")` and `[std::lcm()](../numeric/lcm "cpp/numeric/lcm")` | [P0295R0](https://wg21.link/P0295R0) | 7 | 4 | 19.11\* | Yes | N/A | | 10.3 | | | `[std::not\_fn](../utility/functional/not_fn "cpp/utility/functional/not fn")` | [P0005R4](https://wg21.link/P0005R4)[P0358R1](https://wg21.link/P0358R1) | 7 | 3.9 | 19.12\* | Yes | N/A | | 10.3 | | | [Elementary string conversions](../utility#Elementary_string_conversions "cpp/utility")\* | [P0067R5](https://wg21.link/P0067R5) | 8 (no FP)11 | 7 (no FP)14 (no FP from\_chars) | 19.14\* (no FP)\*19.24\* | 10.0.0\* (no FP). | N/A | | 10.3 (no FP from\_chars) | | | `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr")` with array support | [P0414R2](https://wg21.link/P0414R2) | 7 | 11 | 19.12\* | 12.0.0\* | N/A | | 10.3 | | | [`std::scoped_lock`](../thread/scoped_lock "cpp/thread/scoped lock") | [P0156R2](https://wg21.link/P0156R2) | 7 | 5 | 19.11\* | Yes | N/A | | 10.3 | | | [`std::byte`](../types/byte "cpp/types/byte") | [P0298R3](https://wg21.link/P0298R3) | 7 | 5 | 19.11\* | Yes | N/A | | 10.3 | | | [`std::is_aggregate`](../types/is_aggregate "cpp/types/is aggregate") | [LWG2911](https://cplusplus.github.io/LWG/issue2911) | 7 | 5 | 19.15\* | Yes | N/A | | 10.3 | | | DR: [`std::hash<std::filesystem::path>`](../filesystem/path/hash "cpp/filesystem/path/hash") | [LWG3657](https://cplusplus.github.io/LWG/issue3657) | 12 | | 19.32\* | | N/A | | | | | C++17 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Intel Parallel STL | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | Notes: * As of 2020-11-20, the latest release of Oracle Developer Studio [is 12.6](https://www.oracle.com/application-development/technologies/developerstudio-component-matrix.html). Its [documentation](https://docs.oracle.com/cd/E77782_01/html/E77789/bkaje.html) does not mention C++17. * Cray compiler may have support for some features earlier than 11.0. That version is when it became a derivative of Clang, gaining all of the attendant language feature support of the base compiler. See Cray/HPE document S-2179 [[1]](https://support.hpe.com/hpesc/public/docDisplay?docLocale=en_US&docId=a00123566en_us) cpp Compiler support for C++20 Compiler support for C++20 ========================== ### C++20 core language features | C++20 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Allow [lambda-capture](../language/lambda#Lambda_capture "cpp/language/lambda") `[=, this]` | [P0409R2](https://wg21.link/P0409R2) | 8 | 6 | 19.22\* | 10.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | [`__VA_OPT__`](../preprocessor/replace#Function-like_macros "cpp/preprocessor/replace") | [P0306R4](https://wg21.link/P0306R4)[P1042R1](https://wg21.link/P1042R1) | 8 (partial)\*10 (partial)\*12 | 9 | 19.25\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | [Designated initializers](../language/aggregate_initialization#Designated_initializers "cpp/language/aggregate initialization") | [P0329R4](https://wg21.link/P0329R4) | 4.7 (partial)\*8 | 3.0 (partial)\*10 | 19.21\* | 12.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | [template-parameter-list for generic lambdas](../language/lambda#Syntax "cpp/language/lambda") | [P0428R2](https://wg21.link/P0428R2) | 8 | 9 | 19.22\* | 11.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | [Default member initializers for bit-fields](../language/bit_field#Cpp20_Default_member_initializers_for_bit_fields "cpp/language/bit field") | [P0683R1](https://wg21.link/P0683R1) | 8 | 6 | 19.25\* | 10.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | Initializer list constructors in class template argument deduction | [P0702R1](https://wg21.link/P0702R1) | 8 | 6 | 19.14\* | Yes | 5.0 | 2021.1 | | | | | 20.7 | | | `const&`-qualified pointers to members | [P0704R1](https://wg21.link/P0704R1) | 8 | 6 | 19.0 (2015)\* | 10.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | [Concepts](../language/constraints "cpp/language/constraints") | [P0734R0](https://wg21.link/P0734R0) | 6(TS only)10 | 10 | 19.23\* (partial)\*19.30\* | 12.0.0\* (partial). | 6.1 | 2021.5 | | | | | 20.11 | | | [Lambdas in unevaluated contexts](../language/lambda#Lambdas_in_unevaluated_contexts "cpp/language/lambda") | [P0315R4](https://wg21.link/P0315R4) | 9 | 13 (partial)\*14 (partial)\* | 19.28 (16.8)\* | 13.1.6\* (partial). | | | | | | | | | | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") | [P0515R3](https://wg21.link/P0515R3) | 10 | 8 (partial)10 | 19.20\* | | 5.1 | 2021.1 | | | | | 20.7 | | | DR: Simplifying implicit lambda capture | [P0588R1](https://wg21.link/P0588R1) | 8 | | 19.24\* | | 5.1 | 2021.1 | | | | | 20.7 | | | [init-statements for range-based for](../language/range-for#Syntax "cpp/language/range-for") | [P0614R1](https://wg21.link/P0614R1) | 9 | 8 | 19.25\* | 11.0.0\* | 6.0 | | | | | | 20.11 | | | Default constructible and assignable stateless [lambdas](../language/lambda "cpp/language/lambda") | [P0624R2](https://wg21.link/P0624R2) | 9 | 8 | 19.22\* | 10.0.1\* | 5.1 | 2021.1 | | | | | 20.7 | | | `const` mismatch with defaulted copy constructor | [P0641R2](https://wg21.link/P0641R2) | 9 | 8 | 19.0 (2015)\* | 10.0.1\* | 5.1 | 2021.1 | | | | | 20.7 | | | Access checking on specializations | [P0692R1](https://wg21.link/P0692R1) | Yes | 8 (partial)14 | 19.26\* | 14.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | ADL and function templates that are not visible | [P0846R0](https://wg21.link/P0846R0) | 9 | 9 | 19.21\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | DR: Specify when `constexpr` function definitions are [needed for constant evaluation](../language/constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") | [P0859R0](https://wg21.link/P0859R0) | 5.2 (partial)\*9 | 8 | 19.27\* (partial)\*19.31\* | 11.0.0\* | | | | | | | | | | Attributes `[[[likely](../language/attributes/likely "cpp/language/attributes/likely")]]` and `[[[unlikely](../language/attributes/likely "cpp/language/attributes/likely")]]` | [P0479R5](https://wg21.link/P0479R5) | 9 | 12 | 19.26\* | 13.0.0\* | 5.1 | | | | | | 20.7 | | | Make [`typename`](../keywords/typename "cpp/keywords/typename") more optional | [P0634R3](https://wg21.link/P0634R3) | 9 | | 19.29 (16.10)\* | | 5.1 | | | | | | 20.7 | | | Pack expansion in lambda init-capture | [P0780R2](https://wg21.link/P0780R2) | 9 | 9 | 19.22\* | 11.0.3\* | 6.1 | | | | | | 20.11 | | | Attribute `[[[no\_unique\_address](../language/attributes/no_unique_address "cpp/language/attributes/no unique address")]]` | [P0840R2](https://wg21.link/P0840R2) | 9 | 9 | 19.28 (16.9)\*\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | Conditionally Trivial Special Member Functions | [P0848R3](https://wg21.link/P0848R3) | 10 | 16 | 19.28 (16.8)\* | | 6.1 | | | | | | 20.11 | | | DR: Relaxing the [structured bindings](../language/structured_binding "cpp/language/structured binding") customization point finding rules | [P0961R1](https://wg21.link/P0961R1) | 8 | 8 | 19.21\* | 10.0.1\* | 5.1 | 2021.1 | | | | | 20.7 | | | DR: Relaxing the [range-`for` loop](../language/range-for "cpp/language/range-for") customization point finding rules | [P0962R1](https://wg21.link/P0962R1) | 8 | 8 | 19.25\* | 11.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | DR: Allow structured bindings to accessible members | [P0969R0](https://wg21.link/P0969R0) | 8 | 8 | 19.21\* | 10.0.1\* | 5.1 | 2021.1 | | | | | 20.7 | | | [Destroying `operator delete`](../memory/new/operator_delete "cpp/memory/new/operator delete") | [P0722R3](https://wg21.link/P0722R3) | 9 | 6 | 19.27\* | 10.0.0\* | 6.1 | | | | | | 20.11 | | | Class types in [non-type template parameters](../language/template_parameters#Non-type_template_parameter "cpp/language/template parameters") | [P0732R2](https://wg21.link/P0732R2) | 9 | 12 (partial) | 19.26\*(partial)\*19.28 (16.9)\* | 13.0.0\* (partial). | 6.2 | | | | | | | | | Deprecate implicit [capture](../language/lambda#Lambda_capture "cpp/language/lambda") of `this` via `[=]` | [P0806R2](https://wg21.link/P0806R2) | 9 | 7 | 19.22\* | 10.0.1\* | 5.1 | | | | | | 20.7 | | | [`explicit(bool)`](../language/explicit "cpp/language/explicit") | [P0892R2](https://wg21.link/P0892R2) | 9 | 9 | 19.24\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | Integrating [feature-test macros](../feature_test "cpp/feature test") | [P0941R2](https://wg21.link/P0941R2) | 5 | 3.4 | 19.15\* (partial)19.20\* | Yes | 5.0 | 2021.1 | | | | | 20.7 | | | Prohibit aggregates with user-declared constructors | [P1008R1](https://wg21.link/P1008R1) | 9 | 8 | 19.20\* | 10.0.1\* | 5.1 | 2021.1 | | | | | 20.7 | | | `constexpr` [virtual function](../language/virtual "cpp/language/virtual") | [P1064R0](https://wg21.link/P1064R0) | 9 | 9 | 19.28 (16.9)\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | Consistency improvements for comparisons | [P1120R0](https://wg21.link/P1120R0) | 10 | 8 (partial)10 | 19.22\* | 12.0.0\* | 5.1 | | | | | | 20.7 | | | [`char8_t`](../language/types#char8_t "cpp/language/types") | [P0482R6](https://wg21.link/P0482R6) | 9 | 7\* | 19.22\* | 10.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | [`std::is_constant_evaluated()`](../types/is_constant_evaluated "cpp/types/is constant evaluated") | [P0595R2](https://wg21.link/P0595R2) | 9 | 9 | 19.25\* | 11.0.3\* | 5.1 | 19.1 | | | | | | | | `constexpr` `try`-`catch` blocks | [P1002R1](https://wg21.link/P1002R1) | 9 | 8 | 19.25\* | 10.0.1\* | 5.1 | | | | | | 20.7 | | | [Immediate functions](../language/consteval "cpp/language/consteval") (`consteval`) | [P1073R3](https://wg21.link/P1073R3) | 10 (partial)\* 11 | 11 (partial)14 (partial)\* | 19.28 (16.8)\*\*(partial)19.29 (16.10)\* | 11.0.3\* (partial). | 5.1 | 2021.1 | | | | | 20.7 | | | [Nested inline namespaces](../language/namespace "cpp/language/namespace") | [P1094R2](https://wg21.link/P1094R2) | 9 | 8 | 19.27\* | 10.0.1\* | 5.1 | 2021.1 | | | | | 20.7 | | | Yet another approach for [constrained](../language/template_parameters#Type_template_parameter "cpp/language/template parameters") [declarations](../language/auto "cpp/language/auto") | [P1141R2](https://wg21.link/P1141R2) | 10 | 10 | 19.26\* (partial)19.28 (16.9)\* | 12.0.5\* | 6.1 | | | | | | 20.11 | | | Signed integers are two's complement | [P1236R1](https://wg21.link/P1236R1) | 9 | 9 | Yes | 11.0.3\* | N/A | N/A | | | | | yes | | | [`dynamic_cast`](../language/dynamic_cast "cpp/language/dynamic cast") and polymorphic [`typeid`](../language/typeid "cpp/language/typeid") in [constant expressions](../language/constant_expression "cpp/language/constant expression") | [P1327R1](https://wg21.link/P1327R1) | 10 | 9 | 19.29 (16.10)\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | Changing the active member of a union inside `constexpr` | [P1330R0](https://wg21.link/P1330R0) | 9 | 9 | 19.10\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | [Coroutines](../language/coroutines "cpp/language/coroutines") | [P0912R5](https://wg21.link/P0912R5) | 10 | 8 (partial) | 19.0 (2015)\* (partial)19.10\* (TS only)19.28 (16.8)\* | 10.0.1\* (partial). | 5.1 | 2021.1 | | | | | | | | Parenthesized [initialization of aggregates](../language/aggregate_initialization "cpp/language/aggregate initialization") | [P0960R3](https://wg21.link/P0960R3) | 10 | | 19.28 (16.8)\* | | 5.1 | 2021.1 | | | | | 20.7 | | | DR: Array size deduction in [`new`-expressions](../language/new "cpp/language/new") | [P1009R2](https://wg21.link/P1009R2) | 11 | 9 | 19.27\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | [Modules](../language/modules "cpp/language/modules") | [P1103R3](https://wg21.link/P1103R3) | 11 (partial) | 8 (partial) | 19.0 (2015)\* (partial)19.10\* (TS only)19.28 (16.8)\* | 10.0.1\* (partial). | | | | | | | | | | Stronger Unicode requirements | [P1041R4](https://wg21.link/P1041R4)[P1139R2](https://wg21.link/P1139R2) | 10 | Yes | 19.0 (2015)\* (P1041R4)19.26\* (P1139R2) | Yes | N/A | | | | | | | | | `<=> != ==` | [P1185R2](https://wg21.link/P1185R2) | 10 | 10 | 19.22\* | 12.0.0\* | 5.1 | 2021.1 | | | | | 20.7 | | | DR: Explicitly defaulted functions with different exception specifications | [P1286R2](https://wg21.link/P1286R2) | 10 | 9 | 19.28 (16.8)\* | 11.0.3\* | 5.1 | 2021.1 | | | | | 20.7 | | | Lambda capture and storage class specifiers of structured bindings | [P1091R3](https://wg21.link/P1091R3)[P1381R1](https://wg21.link/P1381R1) | 10 | 8 (partial)16 | 19.11\*(P1381R1)19.24\*(P1091R3) | 10.0.1\* (partial). | 5.1 | 2021.1 | | | | | 20.7 | | | Permit conversions to arrays of unknown bound | [P0388R4](https://wg21.link/P0388R4) | 10 | 14 | 19.27\* | 14.0.0\* | 6.0 | 2021.5 | | | | | 20.11 | | | `constexpr` container operations | [P0784R7](https://wg21.link/P0784R7) | 10 | 10 | 19.28 (16.9)\* | 12.0.0\* | 6.0 | 2021.5 | | | | | 20.11 | | | Deprecating some uses of [`volatile`](../language/cv#Notes "cpp/language/cv") | [P1152R4](https://wg21.link/P1152R4) | 10 | 10 | 19.27\* | 12.0.0\* | 6.0 | 2021.5 | | | | | 20.11 | | | [`constinit`](../language/constinit "cpp/language/constinit") | [P1143R2](https://wg21.link/P1143R2) | 10 | 10 | 19.29 (16.10)\* | 12.0.0\* | 6.1 | | | | | | 20.11 | | | [Deprecate comma operator in subscripts](../language/operator_other#Built-in_comma_operator "cpp/language/operator other") | [P1161R3](https://wg21.link/P1161R3) | 10 | 9 | 19.25\* | 11.0.3\* | 6.0 | 2021.5 | | | | | 20.11 | | | `[[[nodiscard](../language/attributes/nodiscard "cpp/language/attributes/nodiscard")]]` with message | [P1301R4](https://wg21.link/P1301R4) | 10 | 9 | 19.25\* | 11.0.3\* | 6.0 | 2021.5 | | | | | 20.11 | | | Trivial default initialization in `constexpr` functions | [P1331R2](https://wg21.link/P1331R2) | 10 | 10 | 19.27\* | 12.0.0\* | 6.1 | | | | | | 20.11 | | | Unevaluated `asm`-declaration in `constexpr` functions | [P1668R1](https://wg21.link/P1668R1) | 10 | 10 | 19.28 (16.9)\* | 12.0.0\* | 6.1 | | | | | | 20.11 | | | [`using enum`](../language/enum#Using-enum-declaration "cpp/language/enum") | [P1099R5](https://wg21.link/P1099R5) | 11 | 13 | 19.24\* | 13.1.6\* | 6.3 | | | | | | | | | Synthesizing [three-way comparison](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") for specified comparison category | [P1186R3](https://wg21.link/P1186R3) | 11 | 10 | 19.24\* | 12.0.0\* | 6.0 | 2021.5 | | | | | 20.11 | | | DR: `[[[nodiscard](../language/attributes/nodiscard "cpp/language/attributes/nodiscard")]]` for constructors | [P1771R1](https://wg21.link/P1771R1) | 10 | 9 | 19.24\* | 11.0.3\* | 6.0 | 2021.5 | | | | | 20.11 | | | [Class template argument deduction](../language/class_template_argument_deduction "cpp/language/class template argument deduction") for alias templates | [P1814R0](https://wg21.link/P1814R0) | 10 | | 19.27\* | | | | | | | | | | | Class template argument deduction for aggregates | [P1816R0](https://wg21.link/P1816R0)[P2082R1](https://wg21.link/P2082R1) | 10(P1816R0)11(P2082R1) | | 19.27\* | | 6.3 | | | | | | | | | DR: [Implicit move](../language/return "cpp/language/return") for more local objects and rvalue references | [P1825R0](https://wg21.link/P1825R0) | 11\* | 13 | 19.24\* | 13.1.6\* | 6.0 | 2021.5 | | | | | 20.11 | | | Allow defaulting comparisons by value | [P1946R0](https://wg21.link/P1946R0) | 10 | 10 | 19.25\* | 12.0.0\* | 6.1 | | | | | | 20.11 | | | Remove `std::weak_equality` and `std::strong_equality` | [P1959R0](https://wg21.link/P1959R0) | 10 | 10 | 19.25\* | 12.0.0\* | 6.1 | | | | | | 20.11 | | | Inconsistencies with non-type template parameters | [P1907R1](https://wg21.link/P1907R1) | 10 (partial)11 | 12 (partial) | 19.26\* | 13.1.6\* (partial). | 6.2 | | | | | | | | | DR: Pseudo-destructors end object lifetimes | [P0593R6](https://wg21.link/P0593R6) | 11 | 11 | Yes | 12.0.5\* | N/A | N/A | | | | | | | | DR: Converting from `T*` to `bool` should be considered narrowing | [P1957R2](https://wg21.link/P1957R2) | 10\* 11\* | 11 | 19.27\* | 12.0.5\* | 6.1 | | | | | | | | | C++20 feature | Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc | ### C++20 library features | C++20 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | [`std::endian`](../types/endian "cpp/types/endian") | [P0463R1](https://wg21.link/P0463R1) | 8 | 7 | 19.22\* | 10.0.0\* | | | | | Extending `[std::make\_shared()](../memory/shared_ptr/make_shared "cpp/memory/shared ptr/make shared")` to support arrays | [P0674R1](https://wg21.link/P0674R1) | 12 | 15 | 19.27\* | | | | | | [Floating-point atomic](../atomic/atomic#Specializations_for_floating-point_types "cpp/atomic/atomic") | [P0020R6](https://wg21.link/P0020R6) | 10 | | 19.22\* | | | | | | [Synchronized buffered](../io/basic_syncbuf "cpp/io/basic syncbuf") ([`std::basic_osyncstream`](../io/basic_osyncstream "cpp/io/basic osyncstream")) | [P0053R7](https://wg21.link/P0053R7) | 11 | | 19.29 (16.10)\* | | | | | | `constexpr` for [`<algorithm>`](../header/algorithm "cpp/header/algorithm") and [`<utility>`](../header/utility "cpp/header/utility") | [P0202R3](https://wg21.link/P0202R3) | 10 | 8 (partial)12 | 19.26\* | 10.0.1\* (partial) 13.0.0\* | | | | | More `constexpr` for [`<complex>`](../header/complex "cpp/header/complex") | [P0415R1](https://wg21.link/P0415R1) | 9 | 7 (partial) | 19.27\* | 10.0.0\* (partial). | | | | | Make `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")` a scoped enumeration | [P0439R0](https://wg21.link/P0439R0) | 9 | 9 | 19.25\* | 11.0.3\* | | | | | [String](../string/basic_string "cpp/string/basic string") [prefix](../string/basic_string/starts_with "cpp/string/basic string/starts with") and [suffix](../string/basic_string/ends_with "cpp/string/basic string/ends with") checking: [`string`](../string/basic_string/starts_with "cpp/string/basic string/starts with")[`(_view)`](../string/basic_string_view/starts_with "cpp/string/basic string view/starts with") [`::starts_with`](../string/basic_string/starts_with "cpp/string/basic string/starts with")/[`ends_with`](../string/basic_string_view/ends_with "cpp/string/basic string view/ends with") | [P0457R2](https://wg21.link/P0457R2) | 9 | 6 | 19.21\* | 10.0.0\* | | | | | Library support for [`operator<=>`](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") [`<compare>`](../header/compare "cpp/header/compare") | [P0768R1](https://wg21.link/P0768R1) | 10 | 7 (partial)12 | 19.20\* (partial)19.28 (16.9)\* | 13.0.0\* | | | | | [`std::remove_cvref`](../types/remove_cvref "cpp/types/remove cvref") | [P0550R2](https://wg21.link/P0550R2) | 9 | 6 | 19.20\* | 10.0.0\* | | | | | `[[[nodiscard](../language/attributes/nodiscard "cpp/language/attributes/nodiscard")]]` in the [standard library](../language/attributes/nodiscard#Standard_library "cpp/language/attributes/nodiscard") | [P0600R1](https://wg21.link/P0600R1) | 9 | 7 (partial) | 19.13\* (partial)19.22\* | 10.0.0\* (partial). | | | | | Using `std::move` in [numeric algorithms](../numeric "cpp/numeric") | [P0616R0](https://wg21.link/P0616R0) | 9 | 12 | 19.23\* | 13.0.0\* | | | | | [Utility](../memory/to_address "cpp/memory/to address") to convert a pointer to a raw pointer | [P0653R2](https://wg21.link/P0653R2) | 8 | 6 | 19.22\* | Yes | | | | | Atomic [`std::shared_ptr`](../memory/shared_ptr/atomic2 "cpp/memory/shared ptr/atomic2") and [`std::weak_ptr`](../memory/weak_ptr/atomic2 "cpp/memory/weak ptr/atomic2") | [P0718R2](https://wg21.link/P0718R2) | 12 | | 19.27\* | | | | | | [`std::span`](../container/span "cpp/container/span") | [P0122R7](https://wg21.link/P0122R7) | 10 | 7 | 19.26\* | 10.0.0\* | | | | | [Calendar](../chrono#Calendar "cpp/chrono") and [timezone](../chrono#Time_zone "cpp/chrono") | [P0355R7](https://wg21.link/P0355R7) | 11 (partial) | 7 (partial) | 19.29 (16.10)\* | 10.0.0\* (partial). | | | | | [`<version>`](../header/version "cpp/header/version") | [P0754R2](https://wg21.link/P0754R2) | 9 | 7 | 19.22\* | 10.0.0\* | | | | | Comparing unordered containers | [P0809R0](https://wg21.link/P0809R0) | Yes | Yes | 16.0\* | Yes | | | | | [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") requirements | [P0858R0](https://wg21.link/P0858R0) | 9 | 12 | 19.11\* | 13.0.0\* | | | | | `[std::basic\_string::reserve()](../string/basic_string/reserve "cpp/string/basic string/reserve")` should not shrink | [P0966R1](https://wg21.link/P0966R1) | 11 | 8 | 19.25\* | 10.0.1\* | | | | | [Atomic Compare-And-Exchange](../atomic/atomic/compare_exchange "cpp/atomic/atomic/compare exchange") with padding bits | [P0528R3](https://wg21.link/P0528R3) | | | 19.28 (16.8)\* | | | | | | [`std::atomic_ref`](../atomic/atomic_ref "cpp/atomic/atomic ref") | [P0019R8](https://wg21.link/P0019R8) | 10 | | 19.28 (16.8)\* | | | | | | `contains()` member function of associative containers, e.g. [`std::map::contains()`](../container/map/contains "cpp/container/map/contains") | [P0458R2](https://wg21.link/P0458R2) | 9 | 13 | 19.21\* | 13.1.6\* | | | | | DR: Guaranteed copy elision for [piecewise construction](../memory/scoped_allocator_adaptor/construct "cpp/memory/scoped allocator adaptor/construct") | [P0475R1](https://wg21.link/P0475R1) | 9 | Yes | 19.29 (16.10)\* | Yes | | | | | [`std::bit_cast()`](../numeric/bit_cast "cpp/numeric/bit cast") | [P0476R2](https://wg21.link/P0476R2) | 11 | 14 | 19.27\* | | | | | | [Integral power-of-2 operations](../header/bit "cpp/header/bit"): [`std::bit_ceil()`](../numeric/bit_ceil "cpp/numeric/bit ceil"), [`std::bit_floor()`](../numeric/bit_floor "cpp/numeric/bit floor"), [`std::bit_width()`](../numeric/bit_width "cpp/numeric/bit width"), [`std::has_single_bit()`](../numeric/has_single_bit "cpp/numeric/has single bit"). | [P0556R3](https://wg21.link/P0556R3) [P1956R1](https://wg21.link/P1956R1) | 9 (P0556R3)10 (P1956R1) | 9 (P0556R3)12 (P1956R1) | 19.25\* (P0556R3)\*19.27\* (P1956R1)\*19.28 (16.8)\* | 11.0.3\* (P0556R3) 13.0.0\* (P1956R1). | | | | | Improving the return value of erase-like algorithms | [P0646R1](https://wg21.link/P0646R1) | 9 | 10 | 19.21\* | 12.0.0\* | | | | | [`std::destroying_delete`](../memory/new/destroying_delete_t "cpp/memory/new/destroying delete t") | [P0722R3](https://wg21.link/P0722R3) | 9 | 9 | 19.27\* | 11.0.3\* | | | | | [`std::is_nothrow_convertible`](../types/is_convertible "cpp/types/is convertible") | [P0758R1](https://wg21.link/P0758R1) | 9 | 9 | 19.23\* | 11.0.3\* | | | | | Add [`std::shift_left/right`](../algorithm/shift "cpp/algorithm/shift") to [`<algorithm>`](../header/algorithm "cpp/header/algorithm") | [P0769R2](https://wg21.link/P0769R2) | 10 | 12 | 19.21\* | 13.0.0\* | | | | | Constexpr for `[std::swap()](../algorithm/swap "cpp/algorithm/swap")` and `swap` related functions | [P0879R0](https://wg21.link/P0879R0) | 10 | 13 | 19.26\* | 13.1.6\* | | | | | [`std::type_identity`](../types/type_identity "cpp/types/type identity") | [P0887R1](https://wg21.link/P0887R1) | 9 | 8 | 19.21\* | 10.0.1\* | | | | | [Concepts library](../concepts "cpp/concepts") | [P0898R3](https://wg21.link/P0898R3) | 10 | 13 | 19.23\* | 13.1.6\* | | | | | `constexpr` [comparison operators](../container/array/operator_cmp "cpp/container/array/operator cmp") for `[std::array](../container/array "cpp/container/array")` | [P1023R0](https://wg21.link/P1023R0) | 10 | 8 | 19.27\* | 10.0.1\* | | | | | [`std::unwrap_ref_decay` and `std::unwrap_reference`](../utility/functional/unwrap_reference "cpp/utility/functional/unwrap reference") | [P0318R1](https://wg21.link/P0318R1) | 9 | 8 | 19.21\* | 10.0.1\* | | | | | [`std::bind_front()`](../utility/functional/bind_front "cpp/utility/functional/bind front") | [P0356R5](https://wg21.link/P0356R5) | 9 | 13 | 19.25\* | 13.1.6\* | | | | | `[std::reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper")` for incomplete types | [P0357R3](https://wg21.link/P0357R3) | 9 | 8 | 19.26\* | 10.0.1\* | | | | | Fixing [`operator>>(basic_istream&, CharT*)`](../io/basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | [P0487R1](https://wg21.link/P0487R1) | 11 | 8 | 19.23\* | 10.0.1\* | | | | | Library support for [`char8_t`](../language/types#char8_t "cpp/language/types") | [P0482R6](https://wg21.link/P0482R6) | 9 | 8 (partial)\* | 19.22\* | 10.0.1\* (partial). | | | | | [Utility functions](../memory/uses_allocator_construction_args "cpp/memory/uses allocator construction args") to implement [uses-allocator](../memory/make_obj_using_allocator "cpp/memory/make obj using allocator") [construction](../memory/uninitialized_construct_using_allocator "cpp/memory/uninitialized construct using allocator") | [P0591R4](https://wg21.link/P0591R4) | 9 | | 19.29 (16.10)\* | | | | | | DR: `[std::variant](../utility/variant "cpp/utility/variant")` and `[std::optional](../utility/optional "cpp/utility/optional")` should propagate copy/move triviality | [P0602R4](https://wg21.link/P0602R4) | 8.3 | 8 | 19.11\* | 10.0.1\* | | | | | A sane `[std::variant](../utility/variant "cpp/utility/variant")` converting constructor | [P0608R3](https://wg21.link/P0608R3) | 10 | 9 | 19.29 (16.10)\* | 11.0.3\* | | | | | `[std::function](../utility/functional/function "cpp/utility/functional/function")`'s move constructor should be [`noexcept`](../language/noexcept "cpp/language/noexcept") | [P0771R1](https://wg21.link/P0771R1) | 7.2 | 6 | 19.22\* | Yes | | | | | The [One](../iterator "cpp/iterator") [Ranges](../ranges "cpp/ranges") [Proposal](../algorithm/ranges "cpp/algorithm/ranges") | [P0896R4](https://wg21.link/P0896R4) | 10 (partial)\* | 13 (partial)15 | 19.29 (16.10)\* | | | | | | Heterogeneous lookup for [unordered containers](../container#Unordered_associative_containers "cpp/container") | [P0919R3](https://wg21.link/P0919R3) [P1690R1](https://wg21.link/P1690R1) | 11 | 12 | 19.23\* (P0919R3)19.25\* (P1690R1) | 13.0.0\* | | | | | [`<chrono>`](../header/chrono "cpp/header/chrono") `zero()`, `min()`, and `max()` should be [`noexcept`](../language/noexcept "cpp/language/noexcept") | [P0972R0](https://wg21.link/P0972R0) | 9 | 8 | 19.14\* | 10.0.1\* | | | | | `constexpr` in `[std::pointer\_traits](../memory/pointer_traits "cpp/memory/pointer traits")` | [P1006R1](https://wg21.link/P1006R1) | 9 | 8 | 19.26\* | 10.0.1\* | | | | | [`std::assume_aligned()`](../memory/assume_aligned "cpp/memory/assume aligned") | [P1007R3](https://wg21.link/P1007R3) | 9\*11 | 15 | 19.28 (16.9)\* | | | | | | Smart pointer creation with default initialization (e.g. [`make_unique_for_overwrite`](../memory/unique_ptr/make_unique "cpp/memory/unique ptr/make unique")) | [P1020R1](https://wg21.link/P1020R1)[P1973R1](https://wg21.link/P1973R1) | 11 (unique\_ptr)12 (shared\_ptr) | | 19.28 (16.9)\* | | | | | | Misc `constexpr` bits | [P1032R1](https://wg21.link/P1032R1) | 10 | 13 | 19.28 (16.8)\* | 13.1.6\* | | | | | Remove comparison operators of [`std::span`](../container/span "cpp/container/span") | [P1085R2](https://wg21.link/P1085R2) | 10 | 8 | 19.26\* | 10.0.1\* | | | | | Make stateful allocator propagation more consistent for [`operator+(basic_string)`](../string/basic_string/operator_plus_ "cpp/string/basic string/operator+") | [P1165R1](https://wg21.link/P1165R1) | 10 | 15 | 19.26\* | | | | | | Consistent container erasure, e.g. [`std::erase(std::vector)`](../container/vector/erase2 "cpp/container/vector/erase2"), or [`std::erase_if(std::map)`](../container/map/erase_if "cpp/container/map/erase if") | [P1209R0](https://wg21.link/P1209R0) [P1115R3](https://wg21.link/P1115R3) | 9 (P1209R0)10 (P1115R3) | 8 (P1209R0) 11 (P1115R3) | 19.25\* (P1209R0)19.27\* (P1115R3) | 10.0.1\* (P1209R0) 12.0.5\* (P1115R3). | | | | | Standard library header units | [P1502R1](https://wg21.link/P1502R1) | 11 | | 19.29 (16.10)\* | | | | | | [`polymorphic_allocator<>`](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator") as a vocabulary type | [P0339R6](https://wg21.link/P0339R6) | 9 | | 19.28 (16.9)\* | | | | | | [`std::execution::unseq`](../algorithm/execution_policy_tag "cpp/algorithm/execution policy tag") | [P1001R2](https://wg21.link/P1001R2) | 9 | | 19.28 (16.8)\* | | | | | | [`std::lerp()`](../numeric/lerp "cpp/numeric/lerp") and [`std::midpoint()`](../numeric/midpoint "cpp/numeric/midpoint") | [P0811R3](https://wg21.link/P0811R3) | 9 | 9 | 19.23\* (partial)19.28 (16.8)\* | 11.0.3\* | | | | | Usability enhancements for [`std::span`](../container/span "cpp/container/span") | [P1024R3](https://wg21.link/P1024R3) | 10 | 9\*14 | 19.26\* | 11.0.3\* | | | | | DR: Make [`create_directory()`](../filesystem/create_directory "cpp/filesystem/create directory") intuitive | [P1164R1](https://wg21.link/P1164R1) | 8.3 | 12 | 19.20\* | 13.0.0\* | | | | | [`std::ssize()`](../iterator/size "cpp/iterator/size") and unsigned extent for [`std::span`](../container/span "cpp/container/span") | [P1227R2](https://wg21.link/P1227R2) | 10 | 9 | 19.25\* | 11.0.3\* | | | | | Traits for ([un](../types/is_unbounded_array "cpp/types/is unbounded array"))[bounded](../types/is_bounded_array "cpp/types/is bounded array") arrays | [P1357R1](https://wg21.link/P1357R1) | 9 | 9 | 19.25\* | 11.0.3\* | | | | | [`std::to_array()`](../container/array/to_array "cpp/container/array/to array") | [P0325R4](https://wg21.link/P0325R4) | 10 | 10 | 19.25\* | 12.0.0\* | | | | | Efficient access to `[std::basic\_stringbuf](../io/basic_stringbuf "cpp/io/basic stringbuf")`’s buffer | [P0408R7](https://wg21.link/P0408R7) | 11 | | 19.29 (16.10)\* | | | | | | [Layout](../types/is_layout_compatible "cpp/types/is layout compatible")-[compatibility](../types/is_corresponding_member "cpp/types/is corresponding member") and [pointer](../types/is_pointer_interconvertible_base_of "cpp/types/is pointer interconvertible base of")-[interconvertibility](../types/is_pointer_interconvertible_with_class "cpp/types/is pointer interconvertible with class") traits | [P0466R5](https://wg21.link/P0466R5) | 12 | | 19.29 (16.10)\*\* | | | | | | [Bit operations](../numeric#Bit_manipulation_.28since_C.2B.2B20.29 "cpp/numeric"): `std::` [`rotl()`](../numeric/rotl "cpp/numeric/rotl"), [`rotr()`](../numeric/rotr "cpp/numeric/rotr"), [`countl_zero()`](../numeric/countl_zero "cpp/numeric/countl zero"), [`countl_one()`](../numeric/countl_one "cpp/numeric/countl one"), [`countr_zero()`](../numeric/countr_zero "cpp/numeric/countr zero"), [`countr_one()`](../numeric/countr_one "cpp/numeric/countr one"), [`popcount()`](../numeric/popcount "cpp/numeric/popcount"). | [P0553R4](https://wg21.link/P0553R4) | 9 | 9 | 19.25\*\*19.28 (16.8)\* | 11.0.3\* | | | | | [Mathematical constants](../numeric/constants "cpp/numeric/constants") | [P0631R8](https://wg21.link/P0631R8) | 10 | 11 | 19.25\* | 12.0.5\* | | | | | [Text formatting](../utility/format "cpp/utility/format") | [P0645R10](https://wg21.link/P0645R10) | | 14\* | 19.29 (16.10)\* | | | | | | [`std::stop_token`](../thread/stop_token "cpp/thread/stop token") and [`std::jthread`](../thread/jthread "cpp/thread/jthread") | [P0660R10](https://wg21.link/P0660R10) | 10 | | 19.28 (16.9)\* | | | | | | `constexpr` `[std::allocator](../memory/allocator "cpp/memory/allocator")` and related utilities | [P0784R7](https://wg21.link/P0784R7) | 10 | 12 | 19.29 (16.10)\* | 13.0.0\* | | | | | `constexpr` `[std::string](../string/basic_string "cpp/string/basic string")` | [P0980R1](https://wg21.link/P0980R1) | 12 | 15 | 19.29 (16.10)\*19.30\*\* | | | | | | `constexpr` `[std::vector](../container/vector "cpp/container/vector")` | [P1004R2](https://wg21.link/P1004R2) | 12 | 15 | 19.29 (16.10)\*19.30\*\* | | | | | | Input [range adaptors](../ranges "cpp/ranges") | [P1035R7](https://wg21.link/P1035R7) | 10 | | 19.29 (16.10)\* | | | | | | `constexpr` `[std::invoke()](../utility/functional/invoke "cpp/utility/functional/invoke")` and related utilities | [P1065R2](https://wg21.link/P1065R2) | 10 | 12 | 19.28 (16.8)\* | 13.0.0\* | | | | | Atomic waiting and notifying, [`std::counting_semaphore`](../thread/counting_semaphore "cpp/thread/counting semaphore"), [`std::latch`](../thread/latch "cpp/thread/latch") and [`std::barrier`](../thread/barrier "cpp/thread/barrier") | [P1135R6](https://wg21.link/P1135R6) | 11 | 11 | 19.28 (16.8)\* | 13.1.6\* | | | | | [`std::source_location`](../utility/source_location "cpp/utility/source location") | [P1208R6](https://wg21.link/P1208R6) | 11 | 15 (partial)\* | 19.29 (16.10)\* | | | | | | Adding [`<=>`](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") to the standard library | [P1614R2](https://wg21.link/P1614R2) | 10 | 14 (partial)\* | 19.29 (16.10)\* | 13.1.6\* (partial). | | | | | `constexpr` default constructor of `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` and `[std::atomic\_flag](../atomic/atomic_flag "cpp/atomic/atomic flag")` | [P0883R2](https://wg21.link/P0883R2) | 10 | 13 | 19.26\* | 13.1.6\* | | | | | `constexpr` for [numeric algorithms](../numeric#Numeric_operations "cpp/numeric") | [P1645R1](https://wg21.link/P1645R1) | 10 | 12 | 19.26\* | 13.0.0\* | | | | | [Safe integral comparisons](../utility#Integer_comparison_functions "cpp/utility") | [P0586R2](https://wg21.link/P0586R2) | 10 | 13 | 19.27\* | 13.1.6\* | | | | | C++20 feature | Paper(s) | GCC libstdc++ | Clang libc++ | MSVC STL | Apple Clang | Sun/Oracle C++Standard Library | Embarcadero C++ BuilderStandard Library | Cray C++Standard Library |
programming_docs
cpp C++ keywords: protected C++ keywords: protected ======================= ### Usage * [`protected` access specifier](../language/access "cpp/language/access") cpp C++ keywords: asm C++ keywords: asm ================= ### Usage * [Declaration of an inline assembly block](../language/asm "cpp/language/asm") cpp C++ keywords: throw C++ keywords: throw =================== ### Usage * [`throw` expression](../language/throw "cpp/language/throw") | | | | --- | --- | | * [dynamic exception specifications](../language/except_spec "cpp/language/except spec") | (until C++17) | | * [noexcept specifications](../language/noexcept_spec "cpp/language/noexcept spec") | (since C++17)(until C++20) | cpp C++ keywords: dynamic_cast C++ keywords: dynamic\_cast =========================== ### Usage * [`dynamic_cast` type conversion expression](../language/dynamic_cast "cpp/language/dynamic cast"): as the declaration of the expression cpp C++ keywords: case C++ keywords: case ================== ### Usage * [`switch` statement](../language/switch "cpp/language/switch"): as the declaration of the case labels cpp C++ keywords: constexpr (since C++11) C++ keywords: constexpr (since C++11) ===================================== ### Usage * [`constexpr` declaration specifier](../language/constexpr "cpp/language/constexpr") (since C++11) * [constexpr if statement](../language/if "cpp/language/if") (since C++17) * [*lambda-declarator*](../language/lambda "cpp/language/lambda") that explicitly specifies the function call to be a constexpr function (since C++17) cpp C++ keywords: continue C++ keywords: continue ====================== ### Usage * [`continue` statement](../language/continue "cpp/language/continue"): as the declaration of the statement cpp C++ keywords: union C++ keywords: union =================== ### Usage * [declaration of a union type](../language/union "cpp/language/union") * If a function or a variable exists in scope with the name identical to the name of a union type, `union` can be prepended to the name for disambiguation, resulting in an [elaborated type specifier](../language/elaborated_type_specifier "cpp/language/elaborated type specifier") cpp C++ keywords: false C++ keywords: false =================== ### Usage * [boolean literal](../language/bool_literal "cpp/language/bool literal") cpp C++ keywords: compl C++ keywords: compl =================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `~` ### Example ``` #include <iostream> #include <bitset> using bin = std::bitset<8>; void show(bin z, const char* s, int n) { if (n == 0) std::cout << "┌─────────┬──────────┐\n"; if (n <= 2) std::cout << "│ "<<s<<" │ " <<z<<" │\n"; if (n == 2) std::cout << "└─────────┴──────────┘\n"; } int main() { bin x{ "01011010" }; show(x, "x ", 0); bin z = compl x; show(z, "compl x", 2); } ``` Output: ``` ┌─────────┬──────────┐ │ x │ 01011010 │ │ compl x │ 10100101 │ └─────────┴──────────┘ ``` cpp C++ keywords: default C++ keywords: default ===================== ### Usage * [`switch` statement](../language/switch "cpp/language/switch"): as the declaration of the default case label | | | | --- | --- | | * explicitly-defaulted function definition: as an explicit instruction to the compiler to generate [special member function](../language/member_functions#Special_member_functions "cpp/language/member functions") or a [comparison operator](../language/default_comparisons "cpp/language/default comparisons") (since C++20) for a class. | (since C++11) | cpp C++ keywords: final (since C++11) C++ keywords: final (since C++11) ================================= ### Usage * [final specifier](../language/final "cpp/language/final") (since C++11) cpp C++ keywords: decltype (since C++11) C++ keywords: decltype (since C++11) ==================================== ### Usage * [`decltype` specifier](../language/decltype "cpp/language/decltype") (since C++11) * [`decltype(auto)`](../language/auto "cpp/language/auto") (since C++14) cpp C++ keywords: volatile C++ keywords: volatile ====================== ### Usage * [`volatile` type qualifier](../language/cv "cpp/language/cv") * [volatile-qualified member functions](../language/member_functions#const-_and_volatile-qualified_member_functions "cpp/language/member functions") cpp C++ keywords: this C++ keywords: this ================== ### Usage * [`this` pointer](../language/this "cpp/language/this") | | | | --- | --- | | * marking [explicit object parameters](../language/member_functions#Explicit_object_parameter "cpp/language/member functions") | (since C++23) | cpp C++ keywords: typedef C++ keywords: typedef ===================== ### Usage * [`typedef` declaration](../language/typedef "cpp/language/typedef") cpp C++ keywords: mutable C++ keywords: mutable ===================== ### Usage * [`mutable` type specifier](../language/cv "cpp/language/cv") * [*lambda-declarator*](../language/lambda "cpp/language/lambda") that removes `const` qualification from parameters captured by copy (since C++11) cpp C++ keywords: else C++ keywords: else ================== ### Usage * [`if` statement](../language/if "cpp/language/if"): as the declaration of the alternative branch cpp C++ keywords: or_eq C++ keywords: or\_eq ==================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `|=` ### Example ``` #include <iostream> #include <bitset> using bin = std::bitset<8>; void show(bin z, const char* s, int n) { if (n == 0) std::cout << "┌───────────┬──────────┐\n"; if (n <= 2) std::cout << "│ " <<s<< " │ " <<z<<" │\n"; if (n == 2) std::cout << "└───────────┴──────────┘\n"; } int main() { bin x{ "01011010" }; show(x, "x ", 0); bin y{ "00111100" }; show(y, "y ", 1); x or_eq y; show(x, "x or_eq y", 2); } ``` Output: ``` ┌───────────┬──────────┐ │ x │ 01011010 │ │ y │ 00111100 │ │ x or_eq y │ 01111110 │ └───────────┴──────────┘ ``` cpp C++ keywords: while C++ keywords: while =================== ### Usage * [`while` loop](../language/while "cpp/language/while"): as the declaration of the loop * [`do-while` loop](../language/do "cpp/language/do"): as the declaration of the terminating condition of the loop cpp C++ keywords: static_cast C++ keywords: static\_cast ========================== ### Usage * [`static_cast` type conversion expression](../language/static_cast "cpp/language/static cast"): as the declaration of the expression cpp C++ keywords: reflexpr (reflection TS) C++ keywords: reflexpr (reflection TS) ====================================== Experimental Feature The functionality described on this page is part of the Reflection Technical Specification ISO/IEC TS 23619 (reflection TS). ### Usage 1. gets the member list of a [class](class "cpp/keyword/class") type, or the enumerator list of an [enum](enum "cpp/keyword/enum") type. 2. gets the name of type and member. 3. detects whether a data member is [static](static "cpp/keyword/static") or [constexpr](constexpr "cpp/keyword/constexpr"). 4. detects whether member function is [virtual](virtual "cpp/keyword/virtual"), [public](public "cpp/keyword/public"), [protected](protected "cpp/keyword/protected") or [private](private "cpp/keyword/private"). 5. get the *row* and *column* of the source code when the type defines. ### Example `reflexpr` provides us the meta info of the object via *meta-object types*. Note that `std::reflect::get_data_members_t` make programmers able to visit any class just like `[std::tuple](../utility/tuple "cpp/utility/tuple")`. ``` #include <string> #include <vector> struct S { int b; std::string s; std::vector<std::string> v; }; // Reflection TS #include <experimental/reflect> using meta_S = reflexpr(S); using mem = std::reflect::get_data_members_t<meta_S>; using meta = std::reflect::get_data_members_t<mem>; static_assert(std::reflect::is_public_v<meta>); // successful int main() {} ``` We can also know the name info from `reflexpr`: ``` #include <string> #include <string_view> #include <iostream> // Reflection TS #include <experimental/reflect> template <typename Tp> constexpr std::string_view nameof() { using TpInfo = reflexpr(Tp); using aliased_Info = std::experimental::reflect::get_aliased_t<TpInfo>; return std::experimental::reflect::get_name_v<aliased_Info>; } int main(){ std::cout << nameof<std::string>() << '\n'; static_assert(nameof<std::string>() == "basic_string"); // successful } ``` This is an example of getting the *scope* of a type in the [Reflection TS](https://en.cppreference.com/w/cpp/experimental/reflect "cpp/experimental/reflect"). ``` namespace Foo{ struct FooFoo{int FooFooFoo}; } namespace Bar{ using BarBar = ::Foo::FooFoo; } using BarBarInfo = reflexpr(::Bar::BarBar); using BarBarScope = ::std::experimental::reflect::get_scope_t<BarBarInfo>; // Bar, not Foo struct Spam{int SpamSpam;}; struct Grok{ using GrokGrok = Spam::SpamSpam; }; using GrokGrokInfo = reflexpr(::Grok::GrokGrok); using GrokGrokScope = std::experimental::reflect::get_scope_t<GrokGrokInfo>; // Grok, not Spam ``` cpp C++ keywords: alignof (since C++11) C++ keywords: alignof (since C++11) =================================== ### Usage * [`alignof` operator](../language/alignof "cpp/language/alignof") (since C++11) ### Example ``` #include <iostream> #include <cstddef> int main() { std::cout << alignof(std::max_align_t) << '\n'; } ``` Possible output: ``` 16 ``` cpp C++ keywords: module (since C++20) C++ keywords: module (since C++20) ================================== ### Usage * [`module` declaration](../language/modules#Module_declarations "cpp/language/modules"): declares that the current translation unit is a *module unit*. * Starts a [*global module fragment*](../language/modules#Global_module_fragment "cpp/language/modules") of a module unit. * Starts a [*private module fragment*](../language/modules#Private_module_fragment "cpp/language/modules") of a module unit. ### Example ``` module; // starts a global module fragment #include <string> export module foo; // ends a global module fragment // declares the primary module interface unit for named module 'foo' // starts a module unit purview export std::string f(); module :private; // ends the portion of the module interface unit that // can affect the behavior of other translation units // starts a private module fragment std::string f() { return "foo"; } ``` cpp C++ keywords: short C++ keywords: short =================== ### Usage * [`short` type modifier](../language/types "cpp/language/types") cpp C++ keywords: operator C++ keywords: operator ====================== ### Usage * [declaration of an overloaded operator](../language/operators "cpp/language/operators") cpp C++ keywords: namespace C++ keywords: namespace ======================= ### Usage * [namespace declaration](../language/namespace "cpp/language/namespace") * [namespace alias definition](../language/namespace_alias "cpp/language/namespace alias") * [using-directives](../language/namespace#Using-directives "cpp/language/namespace") cpp C++ keywords: co_return (since C++20) C++ keywords: co\_return (since C++20) ====================================== ### Usage * [return statement](../language/return "cpp/language/return") in a [coroutine](../language/coroutines "cpp/language/coroutines") (since C++20) cpp C++ keywords: signed C++ keywords: signed ==================== ### Usage * [`signed` type modifier](../language/types "cpp/language/types") cpp C++ keywords: reinterpret_cast C++ keywords: reinterpret\_cast =============================== ### Usage * [`reinterpret_cast` type conversion expression](../language/reinterpret_cast "cpp/language/reinterpret cast"): as the declaration of the expression cpp C++ keywords: bitor C++ keywords: bitor =================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `|` ### Example ``` #include <iostream> #include <bitset> using bin = std::bitset<8>; void show(bin z, const char* s, int n) { if (n == 0) std::cout << "┌───────────┬──────────┐\n"; if (n <= 2) std::cout << "│ " <<s<< " │ " <<z<<" │\n"; if (n == 2) std::cout << "└───────────┴──────────┘\n"; } int main() { bin x{ "01011010" }; show(x, "x ", 0); bin y{ "00111100" }; show(y, "y ", 1); bin z = x bitor y; show(z, "x bitor y", 2); } ``` Output: ``` ┌───────────┬──────────┐ │ x │ 01011010 │ │ y │ 00111100 │ │ x bitor y │ 01111110 │ └───────────┴──────────┘ ``` cpp C++ keywords: void C++ keywords: void ================== ### Usage * [`void` type](../language/types#Void_type "cpp/language/types") * [parameter list](../language/function#Parameter_list "cpp/language/function") of a function with no parameters cpp C++ keywords: auto C++ keywords: auto ================== ### Usage | | | | --- | --- | | * [automatic storage duration specifier](../language/storage_duration "cpp/language/storage duration") | (until C++11) | | * [`auto` placeholder type specifier](../language/auto "cpp/language/auto") * [function declaration](../language/function "cpp/language/function") with trailing return type | (since C++11) | | * [structured binding declaration](../language/structured_binding "cpp/language/structured binding") | (since C++17) | cpp C++ keywords: public C++ keywords: public ==================== ### Usage * [`public` access specifier](../language/access "cpp/language/access") cpp C++ keywords: int C++ keywords: int ================= ### Usage * [`int` type](../language/types "cpp/language/types"): as the declaration of the type cpp C++ keywords: register C++ keywords: register ====================== ### Usage | | | | --- | --- | | [automatic storage duration specifier](../language/storage_duration "cpp/language/storage duration") (deprecated). | (until C++17) | | The keyword is unused and reserved. | (since C++17) | cpp C++ keywords: catch C++ keywords: catch =================== ### Usage * [`try`-block](../language/try_catch "cpp/language/try catch") * [`function-try`-block](../language/function-try-block "cpp/language/function-try-block") cpp C++ keywords: float C++ keywords: float =================== ### Usage * [`float` type](../language/types "cpp/language/types"): as the name of the type cpp C++ keywords: long C++ keywords: long ================== ### Usage * [`long` type modifier](../language/types "cpp/language/types") cpp C++ keywords: bitand C++ keywords: bitand ==================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `&` ### Example ``` #include <iostream> #include <bitset> using bin = std::bitset<8>; void show(bin z, const char* s, int n) { if (n == 0) std::cout << "┌────────────┬──────────┐\n"; if (n <= 2) std::cout << "│ " <<s<< " │ " <<z<<" │\n"; if (n == 2) std::cout << "└────────────┴──────────┘\n"; } int main() { bin x{ "01011010" }; show(x, "x ", 0); bin y{ "00111100" }; show(y, "y ", 1); bin z = x bitand y; show(z, "x bitand y", 2); } ``` Output: ``` ┌────────────┬──────────┐ │ x │ 01011010 │ │ y │ 00111100 │ │ x bitand y │ 00011000 │ └────────────┴──────────┘ ``` cpp C++ keywords: friend C++ keywords: friend ==================== ### Usage * [`friend` specifier](../language/friend "cpp/language/friend") cpp C++ keywords: virtual C++ keywords: virtual ===================== ### Usage * [virtual function specifier](../language/virtual "cpp/language/virtual") * [virtual base class specifier](../language/derived_class "cpp/language/derived class") cpp C++ keywords: co_await (since C++20) C++ keywords: co\_await (since C++20) ===================================== The unary operator `co_await` suspends a [`coroutine`](../coroutine "cpp/coroutine") and returns control to the caller. ### Usage * [`co_await` expression](../language/coroutines#co_await "cpp/language/coroutines") (since C++20) cpp C++ keywords: class C++ keywords: class =================== ### Usage * [declaration of a class](../language/class "cpp/language/class") | | | | --- | --- | | * [declaration of a scoped enumeration type](../language/enum "cpp/language/enum") | (since C++11) | * In a [template declaration](../language/templates "cpp/language/templates"), `class` can be used to introduce [type template parameters](../language/template_parameters#Type_template_parameter "cpp/language/template parameters") and [template template parameters](../language/template_parameters#Template_template_parameter "cpp/language/template parameters") * If a function or a variable exists in scope with the name identical to the name of a class type, `class` can be prepended to the name for disambiguation, resulting in an [elaborated type specifier](../language/elaborated_type_specifier "cpp/language/elaborated type specifier") ### Example ``` class Foo; // forward declaration of a class class Bar { // definition of a class public: Bar(int i) : m_i(i) {} private: int m_i; }; template <class T> // template argument void qux() { T t; } enum class Pub { // scoped enum, since C++11 b, d, p, q }; int main() { Bar Bar(1); class Bar Bar2(2); // elaborated type } ``` cpp C++ keywords: typeid C++ keywords: typeid ==================== ### Usage * [`typeid` operator](../language/typeid "cpp/language/typeid") cpp C++ keywords: true C++ keywords: true ================== ### Usage * [boolean literal](../language/bool_literal "cpp/language/bool literal") cpp C++ keywords: override (since C++11) C++ keywords: override (since C++11) ==================================== ### Usage * [override specifier](../language/override "cpp/language/override") (since C++11) cpp C++ keywords: char8_t (since C++20) C++ keywords: char8\_t (since C++20) ==================================== ### Usage * [`char8_t` type](../language/types#char8_t "cpp/language/types"): as the declaration of the type (since C++20) cpp C++ keywords: consteval (since C++20) C++ keywords: consteval (since C++20) ===================================== ### Usage * [`consteval` declaration specifier](../language/consteval "cpp/language/consteval") (since C++20) * [*lambda-declarator*](../language/lambda "cpp/language/lambda") that explicitly specifies the function call to be an immediate function (since C++20) * [consteval if](../language/if#Consteval_if "cpp/language/if") statement (since C++23) cpp C++ keywords: and C++ keywords: and ================= ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `&&` [(Logical AND operator)](../language/operator_logical "cpp/language/operator logical") ### Example ``` #include <iostream> #include <string> void truth_table_entry(bool const x, bool const y) { const std::string s[] = {"false ", "true ", "and ", " "}; const std::string x_and_y = s[x] + s[2] + s[y]; const std::string r = s[x and y] + s[3]; if (x + y == 0) std::cout << "┌──────────────────┬─────────┐\n"; if (x + y <= 2) std::cout << "│ " << x_and_y <<" │ "<<r<<" │\n"; if (x + y == 2) std::cout << "└──────────────────┴─────────┘\n"; } int main() { truth_table_entry(false, false); truth_table_entry(false, true ); truth_table_entry(true , false); truth_table_entry(true , true ); } ``` Output: ``` ┌──────────────────┬─────────┐ │ false and false │ false │ │ false and true │ false │ │ true and false │ false │ │ true and true │ true │ └──────────────────┴─────────┘ ```
programming_docs
cpp C++ keywords: and_eq C++ keywords: and\_eq ===================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `&=` ### Example ``` #include <iostream> #include <bitset> int main() { std::bitset<4> mask("1100"); std::bitset<4> val("0111"); val and_eq mask; std::cout << val << '\n'; } ``` Output: ``` 0100 ``` cpp C++ keywords: constinit (since C++20) C++ keywords: constinit (since C++20) ===================================== ### Usage * [`constinit` declaration specifier](../language/constinit "cpp/language/constinit") (since C++20) cpp C++ keywords: double C++ keywords: double ==================== ### Usage * [`double` type](../language/types "cpp/language/types"): as the declaration of the type * [`long double` type](../language/types "cpp/language/types"): as the declaration of the type when combined with [`long`](long "cpp/keyword/long") cpp C++ keywords: xor_eq C++ keywords: xor\_eq ===================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `^=` ### Example ``` #include <iostream> #include <bitset> using bin = std::bitset<8>; void show(bin z, const char* s, int n) { if (n == 0) std::cout << "┌────────────┬──────────┐\n"; if (n <= 2) std::cout << "│ " <<s<< " │ " <<z<<" │\n"; if (n == 2) std::cout << "└────────────┴──────────┘\n"; } int main() { bin x{ "01011010" }; show(x, "x ", 0); bin y{ "00111100" }; show(y, "y ", 1); x xor_eq y; show(x, "x xor_eq y", 2); } ``` Output: ``` ┌────────────┬──────────┐ │ x │ 01011010 │ │ y │ 00111100 │ │ x xor_eq y │ 01100110 │ └────────────┴──────────┘ ``` cpp C++ keywords: char32_t (since C++11) C++ keywords: char32\_t (since C++11) ===================================== ### Usage * [`char32_t` type](../language/types#char32_t "cpp/language/types"): as the declaration of the type (since C++11) cpp C++ keywords: extern C++ keywords: extern ==================== ### Usage * [static storage duration with *external* linkage specifier](../language/storage_duration "cpp/language/storage duration") * [language linkage](../language/language_linkage "cpp/language/language linkage") specification * explicit template instantiation declaration (or "extern template") + [for class templates](../language/class_template#Class_template_instantiation "cpp/language/class template") + [for function templates](../language/function_template#Function_template_instantiation "cpp/language/function template") cpp C++ keywords: import (since C++20) C++ keywords: import (since C++20) ================================== ### Usage * [`module` *import declaration*](../language/modules#Importing_modules_and_headers "cpp/language/modules"): imports a set of translation units (since C++20) ### Example ``` export module foo; import bar; // imports all module interface units of module bar import :baz; // imports the so-named module partition baz of module foo import <set>; // imports a synthesized header unit formed from header <set> ``` cpp C++ keywords: enum C++ keywords: enum ================== ### Usage * [declaration of an enumeration type](../language/enum "cpp/language/enum") cpp C++ keywords: const_cast C++ keywords: const\_cast ========================= ### Usage * [`const_cast` type conversion expression](../language/const_cast "cpp/language/const cast"): as the declaration of the expression cpp C++ keywords: char C++ keywords: char ================== ### Usage * [`char` type](../language/types "cpp/language/types"): as the declaration of the type cpp C++ keywords: xor C++ keywords: xor ================= ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `^` ### Example ``` #include <iostream> #include <bitset> using bin = std::bitset<8>; void show(bin z, const char* s, int n) { if (n == 0) std::cout << "┌─────────┬──────────┐\n"; if (n <= 2) std::cout << "│ "<<s<<" │ " <<z<<" │\n"; if (n == 2) std::cout << "└─────────┴──────────┘\n"; } int main() { bin x{ "01011010" }; show(x, "x ", 0); bin y{ "00111100" }; show(y, "y ", 1); bin z = x xor y; show(z, "x xor y", 2); } ``` Output: ``` ┌─────────┬──────────┐ │ x │ 01011010 │ │ y │ 00111100 │ │ x xor y │ 01100110 │ └─────────┴──────────┘ ``` cpp C++ keywords: char16_t (since C++11) C++ keywords: char16\_t (since C++11) ===================================== ### Usage * [`char16_t` type](../language/types#char16_t "cpp/language/types"): as the declaration of the type (since C++11) cpp C++ keywords: alignas (since C++11) C++ keywords: alignas (since C++11) =================================== ### Usage * [`alignas` specifier](../language/alignas "cpp/language/alignas") (since C++11) cpp C++ keywords: static_assert (since C++11) C++ keywords: static\_assert (since C++11) ========================================== ### Usage * [`static_assert` declaration](../language/static_assert "cpp/language/static assert") (since C++11) cpp C++ keywords: private C++ keywords: private ===================== ### Usage * [`private` access specifier](../language/access "cpp/language/access") cpp C++ keywords: noexcept (since C++11) C++ keywords: noexcept (since C++11) ==================================== ### Usage * [`noexcept` operator](../language/noexcept "cpp/language/noexcept") (since C++11) * [`noexcept` specifier](../language/noexcept_spec "cpp/language/noexcept spec") (since C++11) cpp C++ keywords: inline C++ keywords: inline ==================== ### Usage * [`inline` specifier](../language/inline "cpp/language/inline") for functions and variables (since C++17) * [`inline namespace`](../language/namespace "cpp/language/namespace") definition (since C++11) cpp C++ keywords: sizeof C++ keywords: sizeof ==================== ### Usage * [`sizeof` operator](../language/sizeof "cpp/language/sizeof") * [`sizeof...` operator](../language/sizeof... "cpp/language/sizeof...") (since C++11) cpp C++ keywords: goto C++ keywords: goto ================== ### Usage * [`goto` statement](../language/goto "cpp/language/goto"): as the declaration of the statement cpp C++ keywords: static C++ keywords: static ==================== ### Usage * [declarations of namespace members with static storage duration and internal linkage](../language/storage_duration "cpp/language/storage duration") * [definitions of block scope variables with static storage duration and initialized once](../language/storage_duration#Static_local_variables "cpp/language/storage duration") * [declarations of class members not bound to specific instances](../language/static "cpp/language/static") cpp C++ keywords: not C++ keywords: not ================= ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `!` ### Example ``` #include <iostream> void show(bool z, const char* s, int n) { const char* r{z ? " true " : " false "}; if (n == 0) std::cout << "┌───────────┬─────────┐\n"; if (n <= 1) std::cout << "│ " <<s<< " │ "<<r<<" │\n"; if (n == 1) std::cout << "└───────────┴─────────┘\n"; } int main() { show(not true , "not true ", 0); show(not false, "not false", 1); } ``` Output: ``` ┌───────────┬─────────┐ │ not true │ false │ │ not false │ true │ └───────────┴─────────┘ ``` cpp C++ keywords: template C++ keywords: template ====================== ### Usage * [Declaration of a template](../language/templates "cpp/language/templates") * Inside a template definition, `template` can be used to declare that a [dependent name](../language/dependent_name "cpp/language/dependent name") is a template. cpp C++ keywords: explicit C++ keywords: explicit ====================== ### Usage * [explicit specifier](../language/explicit "cpp/language/explicit") cpp C++ keywords: thread_local (since C++11) C++ keywords: thread\_local (since C++11) ========================================= ### Usage * [thread local storage duration specifier](../language/storage_duration "cpp/language/storage duration") (since C++11) ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/thread_local "c/thread/thread local") for `thread_local` | cpp C++ keywords: wchar_t C++ keywords: wchar\_t ====================== ### Usage * [`wchar_t` type](../language/types "cpp/language/types"): as the declaration of the type cpp C++ keywords: bool C++ keywords: bool ================== ### Usage * [`bool` type](../language/types "cpp/language/types"): as the declaration of the type cpp C++ keywords: return C++ keywords: return ==================== ### Usage * [`return` statement](../language/return "cpp/language/return"): as the declaration of the statement cpp C++ keywords: using C++ keywords: using =================== ### Usage * [using-directives](../language/namespace#Using-directives "cpp/language/namespace") for namespaces and [using-declarations](../language/namespace "cpp/language/namespace") for namespace members * [using-declarations](../language/using_declaration "cpp/language/using declaration") for class members * [using-enum-declarations](../language/enum#Using-enum-declaration "cpp/language/enum") for enumerators (since C++20) * [type alias and alias template declaration](../language/type_alias "cpp/language/type alias") (since C++11) cpp C++ keywords: export C++ keywords: export ==================== ### Usage | | | | --- | --- | | Used to mark a [template definition](../language/class_template "cpp/language/class template") *exported*, which allows the same template to be declared, but not defined, in other translation units. | (until C++11) | | The keyword is unused and reserved. | (since C++11)(until C++20) | | Marks a declaration, a group of declarations, or another [module](../language/modules "cpp/language/modules") as exported by the current [module](../language/modules "cpp/language/modules"). | (since C++20) | cpp C++ keywords: break C++ keywords: break =================== ### Usage * [`break` statement](../language/break "cpp/language/break"): as the declaration of the statement cpp C++ keywords: unsigned C++ keywords: unsigned ====================== ### Usage * [`unsigned` type modifier](../language/types "cpp/language/types") cpp C++ keywords: if C++ keywords: if ================ ### Usage * [`if` statement](../language/if "cpp/language/if"): as the declaration of the `if` statement cpp C++ keywords: const C++ keywords: const =================== ### Usage * [`const` type qualifier](../language/cv "cpp/language/cv") * [const-qualified member functions](../language/member_functions#const-_and_volatile-qualified_member_functions "cpp/language/member functions") cpp C++ keywords: delete C++ keywords: delete ==================== ### Usage * [`delete` expression](../language/delete "cpp/language/delete") * [deallocation functions](../memory/new/operator_delete "cpp/memory/new/operator delete") as the name of operator-like functions | | | | --- | --- | | * [deleted functions](../language/function#Deleted_functions "cpp/language/function") | (since C++11) | cpp C++ keywords: struct C++ keywords: struct ==================== ### Usage * [declaration of a compound type](../language/class "cpp/language/class") | | | | --- | --- | | * [declaration of a scoped enumeration type](../language/enum "cpp/language/enum") | (since C++11) | * If a function or a variable exists in scope with the name identical to the name of a non-union class type, `struct` can be prepended to the name for disambiguation, resulting in an [elaborated type specifier](../language/elaborated_type_specifier "cpp/language/elaborated type specifier") cpp C++ keywords: try C++ keywords: try ================= ### Usage * [`try`-block](../language/try_catch "cpp/language/try catch") * [`function-try`-block](../language/function-try-block "cpp/language/function-try-block") cpp C++ keywords: concept (since C++20) C++ keywords: concept (since C++20) =================================== ### Usage * declares a [named type requirement](../language/constraints "cpp/language/constraints") (since C++20) cpp C++ keywords: co_yield (since C++20) C++ keywords: co\_yield (since C++20) ===================================== ### Usage * [yields a value from a coroutine](../language/coroutines "cpp/language/coroutines") (since C++20) cpp C++ keywords: switch C++ keywords: switch ==================== ### Usage * [`switch` statement](../language/switch "cpp/language/switch"): as the declaration of the statement cpp C++ keywords: or C++ keywords: or ================ ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `||` ### Example ``` #include <iostream> void show(bool z, const char* s, int n) { const char* r{z ? " true " : " false "}; if (n == 0) std::cout << "┌────────────────┬─────────┐\n"; if (n <= 2) std::cout << "│ " <<s<< " │ "<<r<<" │\n"; if (n == 2) std::cout << "└────────────────┴─────────┘\n"; } int main() { show(false or false, "false or false", 0); show(false or true , "false or true ", 1); show(true or false, "true or false", 1); show(true or true , "true or true ", 2); } ``` Output: ``` ┌────────────────┬─────────┐ │ false or false │ false │ │ false or true │ true │ │ true or false │ true │ │ true or true │ true │ └────────────────┴─────────┘ ``` cpp C++ keywords: requires (since C++20) C++ keywords: requires (since C++20) ==================================== ### Usage * specifies a constant expression on template parameters that [evaluate a requirement](../language/requires "cpp/language/requires") (since C++20) * in a template declaration, specifies an [associated constraint](../language/constraints "cpp/language/constraints") (since C++20) cpp C++ keywords: not_eq C++ keywords: not\_eq ===================== ### Usage * [alternative operators](../language/operator_alternative "cpp/language/operator alternative"): as an alternative for `!=` ### Example ``` #include <iostream> void show(bool z, const char* s, int n) { const char* r { z ? " true " : " false " }; if (n == 0) std::cout << "┌────────────────────┬─────────┐\n"; if (n <= 2) std::cout << "│ " <<s<< " │ "<<r<<" │\n"; if (n == 2) std::cout << "└────────────────────┴─────────┘\n"; } int main() { show(false not_eq false, "false not_eq false", 0); show(false not_eq true , "false not_eq true ", 1); show(true not_eq false, "true not_eq false", 1); show(true not_eq true , "true not_eq true ", 2); } ``` Output: ``` ┌────────────────────┬─────────┐ │ false not_eq false │ false │ │ false not_eq true │ true │ │ true not_eq false │ true │ │ true not_eq true │ false │ └────────────────────┴─────────┘ ``` cpp C++ keywords: do C++ keywords: do ================ ### Usage * [`do-while` loop](../language/do "cpp/language/do"): as the declaration of the loop cpp C++ keywords: for C++ keywords: for ================= ### Usage * [`for` loop](../language/for "cpp/language/for"): as the declaration of the loop * [range-based `for` loop](../language/range-for "cpp/language/range-for"): as the declaration of the loop (since C++11) cpp C++ keywords: typename C++ keywords: typename ====================== ### Usage * In the template parameter list of a [template declaration](../language/templates "cpp/language/templates"), `typename` can be used as an alternative to [class](../keyword/class "cpp/keyword/class") to declare [type template parameters](../language/template_parameters#Type_template_parameter "cpp/language/template parameters") and template template parameters (since C++17). * Inside a declaration or a definition of a template, `typename` can be used to declare that a [dependent qualified name](../language/dependent_name "cpp/language/dependent name") is a type. * Inside a declaration or a definition of a template, (until C++11) `typename` can be used before a non-dependent qualified type name. It has no effect in this case. * Inside a [requirements](../language/constraints "cpp/language/constraints") for type requirements (since C++20) cpp std::async std::async ========== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | | (1) | | | ``` template< class Function, class... Args > std::future<typename std::result_of<typename std::decay<Function>::type( typename std::decay<Args>::type...)>::type> async( Function&& f, Args&&... args ); ``` | (since C++11) (until C++17) | | ``` template< class Function, class... Args > std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>> async( Function&& f, Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template< class Function, class... Args > [[nodiscard]] std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>> async( Function&& f, Args&&... args ); ``` | (since C++20) | | | (2) | | | ``` template< class Function, class... Args > std::future<typename std::result_of<typename std::decay<Function>::type( typename std::decay<Args>::type...)>::type> async( std::launch policy, Function&& f, Args&&... args ); ``` | (since C++11) (until C++17) | | ``` template< class Function, class... Args > std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>> async( std::launch policy, Function&& f, Args&&... args ); ``` | (since C++17) (until C++20) | | ``` template< class Function, class... Args > [[nodiscard]] std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>> async( std::launch policy, Function&& f, Args&&... args ); ``` | (since C++20) | The function template `async` runs the function `f` asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a `[std::future](future "cpp/thread/future")` that will eventually hold the result of that function call. 1) Behaves as if (2) is called with `policy` being `[std::launch::async](http://en.cppreference.com/w/cpp/thread/launch) | [std::launch::deferred](http://en.cppreference.com/w/cpp/thread/launch)`. 2) Calls a function `f` with arguments `args` according to a specific launch policy `policy`. * If the *async* flag is set (i.e. `(policy & [std::launch::async](http://en.cppreference.com/w/cpp/thread/launch)) != 0`), then `async` executes the callable object `f` on a new thread of execution (with all thread-locals initialized) as if spawned by `[std::thread](http://en.cppreference.com/w/cpp/thread/thread)([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...)`, except that if the function `f` returns a value or throws an exception, it is stored in the shared state accessible through the `[std::future](future "cpp/thread/future")` that `async` returns to the caller. * If the *deferred* flag is set (i.e. `(policy & [std::launch::deferred](http://en.cppreference.com/w/cpp/thread/launch)) != 0`), then `async` converts `f` and `args...` the same way as by `[std::thread](thread "cpp/thread/thread")` constructor, but does not spawn a new thread of execution. Instead, *lazy evaluation* is performed: the first call to a non-timed wait function on the `[std::future](future "cpp/thread/future")` that `async` returned to the caller will cause the copy of `f` to be invoked (as an rvalue) with the copies of `args...` (also passed as rvalues) in the current thread (which does not have to be the thread that originally called `std::async`). The result or exception is placed in the shared state associated with the future and only then it is made ready. All further accesses to the same `[std::future](future "cpp/thread/future")` will return the result immediately. * If neither `[std::launch::async](launch "cpp/thread/launch")` nor `[std::launch::deferred](launch "cpp/thread/launch")`, nor any implementation-defined policy flag is set in `policy`, the behavior is undefined. If more than one flag is set, it is implementation-defined which policy is selected. For the default (both the `[std::launch::async](launch "cpp/thread/launch")` and `[std::launch::deferred](launch "cpp/thread/launch")` flags are set in `policy`), standard recommends (but doesn't require) utilizing available concurrency, and deferring any additional tasks. In any case, the call to `std::async` *synchronizes-with* (as defined in `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the call to `f`, and the completion of `f` is *sequenced-before* making the shared state ready. If the `async` policy is chosen, the associated thread completion *synchronizes-with* the successful return from the first function that is waiting on the shared state, or with the return of the last function that releases the shared state, whichever comes first. If `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Function>::type` or each type in `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Args>::type` is not constructible from its corresponding argument, the program is ill-formed. ### Parameters | | | | | --- | --- | --- | | f | - | [Callable](../named_req/callable "cpp/named req/Callable") object to call | | args... | - | parameters to pass to `f` | | policy | - | bitmask value, where individual bits control the allowed methods of execution | Bit | Explanation | | --- | --- | | `[std::launch::async](launch "cpp/thread/launch")` | enable asynchronous evaluation | | `[std::launch::deferred](launch "cpp/thread/launch")` | enable lazy evaluation | | ### Return value `[std::future](future "cpp/thread/future")` referring to the shared state created by this call to `std::async`. ### Exceptions Throws `[std::system\_error](../error/system_error "cpp/error/system error")` with error condition `[std::errc::resource\_unavailable\_try\_again](../error/errc "cpp/error/errc")` if the launch policy equals `[std::launch::async](launch "cpp/thread/launch")` and the implementation is unable to start a new thread (if the policy is `async|deferred` or has additional bits set, it will fall back to deferred or the implementation-defined policies in this case), or `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory for the internal data structures could not be allocated. ### Notes The implementation may extend the behavior of the first overload of `std::async` by enabling additional (implementation-defined) bits in the default launch policy. Examples of implementation-defined launch policies are the sync policy (execute immediately, within the async call) and the task policy (similar to async, but thread-locals are not cleared). If the `std::future` obtained from `std::async` is not moved from or bound to a reference, the destructor of the `[std::future](future "cpp/thread/future")` will block at the end of the full expression until the asynchronous operation completes, essentially making code such as the following synchronous: ``` std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f() std::async(std::launch::async, []{ g(); }); // does not start until f() completes ``` (note that the destructors of std::futures obtained by means other than a call to std::async never block). ### Example ``` #include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <future> #include <string> #include <mutex> std::mutex m; struct X { void foo(int i, const std::string& str) { std::lock_guard<std::mutex> lk(m); std::cout << str << ' ' << i << '\n'; } void bar(const std::string& str) { std::lock_guard<std::mutex> lk(m); std::cout << str << '\n'; } int operator()(int i) { std::lock_guard<std::mutex> lk(m); std::cout << i << '\n'; return i + 10; } }; template <typename RandomIt> int parallel_sum(RandomIt beg, RandomIt end) { auto len = end - beg; if (len < 1000) return std::accumulate(beg, end, 0); RandomIt mid = beg + len/2; auto handle = std::async(std::launch::async, parallel_sum<RandomIt>, mid, end); int sum = parallel_sum(beg, mid); return sum + handle.get(); } int main() { std::vector<int> v(10000, 1); std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n'; X x; // Calls (&x)->foo(42, "Hello") with default policy: // may print "Hello 42" concurrently or defer execution auto a1 = std::async(&X::foo, &x, 42, "Hello"); // Calls x.bar("world!") with deferred policy // prints "world!" when a2.get() or a2.wait() is called auto a2 = std::async(std::launch::deferred, &X::bar, x, "world!"); // Calls X()(43); with async policy // prints "43" concurrently auto a3 = std::async(std::launch::async, X(), 43); a2.wait(); // prints "world!" std::cout << a3.get() << '\n'; // prints "53" } // if a1 is not done at this point, destructor of a1 prints "Hello 42" here ``` Possible output: ``` The sum is 10000 43 world! 53 Hello 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 2021](https://cplusplus.github.io/LWG/issue2021) | C++11 | return type incorrect and value categoryof arguments unclear in the deferred case | corrected return type andclarified that rvalues are used | | [LWG 2120](https://cplusplus.github.io/LWG/issue2120) | C++11 | the behavior was unclear if no standard orimplementation-defined policy is set | the behavior is undefined | | [LWG 3476](https://cplusplus.github.io/LWG/issue3476) | C++11 | `Function` and `Args...` were required to be [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible")while no additional move constructions specified | requirements removed | ### See also | | | | --- | --- | | [future](future "cpp/thread/future") (C++11) | waits for a value that is set asynchronously (class template) |
programming_docs
cpp std::future std::future =========== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` template< class T > class future; ``` | (1) | (since C++11) | | ``` template< class T > class future<T&>; ``` | (2) | (since C++11) | | ``` template<> class future<void>; ``` | (3) | (since C++11) | The class template `std::future` provides a mechanism to access the result of asynchronous operations: * An asynchronous operation (created via `[std::async](async "cpp/thread/async")`, `[std::packaged\_task](packaged_task "cpp/thread/packaged task")`, or `[std::promise](promise "cpp/thread/promise")`) can provide a `std::future` object to the creator of that asynchronous operation. * The creator of the asynchronous operation can then use a variety of methods to query, wait for, or extract a value from the `std::future`. These methods may block if the asynchronous operation has not yet provided a value. * When the asynchronous operation is ready to send a result to the creator, it can do so by modifying *shared state* (e.g. `[std::promise::set\_value](promise/set_value "cpp/thread/promise/set value")`) that is linked to the creator's `std::future`. Note that `std::future` references shared state that is not shared with any other asynchronous return objects (as opposed to `[std::shared\_future](shared_future "cpp/thread/shared future")`). ### Member functions | | | | --- | --- | | [(constructor)](future/future "cpp/thread/future/future") | constructs the future object (public member function) | | [(destructor)](future/~future "cpp/thread/future/~future") | destructs the future object (public member function) | | [operator=](future/operator= "cpp/thread/future/operator=") | moves the future object (public member function) | | [share](future/share "cpp/thread/future/share") | transfers the shared state from `*this` to a [`shared_future`](shared_future "cpp/thread/shared future") and returns it (public member function) | | Getting the result | | [get](future/get "cpp/thread/future/get") | returns the result (public member function) | | State | | [valid](future/valid "cpp/thread/future/valid") | checks if the future has a shared state (public member function) | | [wait](future/wait "cpp/thread/future/wait") | waits for the result to become available (public member function) | | [wait\_for](future/wait_for "cpp/thread/future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function) | | [wait\_until](future/wait_until "cpp/thread/future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function) | ### Examples ``` #include <iostream> #include <future> #include <thread> int main() { // future from a packaged_task std::packaged_task<int()> task([]{ return 7; }); // wrap the function std::future<int> f1 = task.get_future(); // get a future std::thread t(std::move(task)); // launch on a thread // future from an async() std::future<int> f2 = std::async(std::launch::async, []{ return 8; }); // future from a promise std::promise<int> p; std::future<int> f3 = p.get_future(); std::thread( [&p]{ p.set_value_at_thread_exit(9); }).detach(); std::cout << "Waiting..." << std::flush; f1.wait(); f2.wait(); f3.wait(); std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; t.join(); } ``` Output: ``` Waiting...Done! Results are: 7 8 9 ``` #### Example with exceptions ``` #include <thread> #include <iostream> #include <future> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p]{ try { // code that may throw throw std::runtime_error("Example"); } catch(...) { try { // store anything thrown in the promise p.set_exception(std::current_exception()); } catch(...) {} // set_exception() may throw too } }); try { std::cout << f.get(); } catch(const std::exception& e) { std::cout << "Exception from the thread: " << e.what() << '\n'; } t.join(); } ``` Output: ``` Exception from the thread: Example ``` ### See also | | | | --- | --- | | [async](async "cpp/thread/async") (C++11) | runs a function asynchronously (potentially in a new thread) and returns a `std::future` that will hold the result (function template) | | [shared\_future](shared_future "cpp/thread/shared future") (C++11) | waits for a value (possibly referenced by other futures) that is set asynchronously (class template) | cpp std::this_thread::sleep_for std::this\_thread::sleep\_for ============================= | Defined in header `[<thread>](../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` template< class Rep, class Period > void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration ); ``` | | (since C++11) | Blocks the execution of the current thread for *at least* the specified `sleep_duration`. This function may block for longer than `sleep_duration` due to scheduling or resource contention delays. The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments. ### Parameters | | | | | --- | --- | --- | | sleep\_duration | - | time duration to sleep. | ### Return value (none). ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example ``` #include <iostream> #include <chrono> #include <thread> int main() { using namespace std::chrono_literals; std::cout << "Hello waiter\n" << std::flush; auto start = std::chrono::high_resolution_clock::now(); std::this_thread::sleep_for(2000ms); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> elapsed = end-start; std::cout << "Waited " << elapsed.count() << " ms\n"; } ``` Possible output: ``` Hello waiter Waited 2000.12 ms ``` ### See also | | | | --- | --- | | [sleep\_until](sleep_until "cpp/thread/sleep until") (C++11) | stops the execution of the current thread until a specified time point (function) | cpp std::shared_timed_mutex std::shared\_timed\_mutex ========================= | Defined in header `[<shared\_mutex>](../header/shared_mutex "cpp/header/shared mutex")` | | | | --- | --- | --- | | ``` class shared_timed_mutex; ``` | | (since C++14) | The `shared_timed_mutex` class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In contrast to other mutex types which facilitate exclusive access, a `shared_timed_mutex` has two levels of access: * *exclusive* - only one thread can own the mutex. * *shared* - several threads can share ownership of the same mutex. Shared mutexes are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do so. In a manner similar to [`timed_mutex`](timed_mutex "cpp/thread/timed mutex"), `shared_timed_mutex` provides the ability to attempt to claim ownership of a `shared_timed_mutex` with a timeout via the [`try_lock_for()`](shared_timed_mutex/try_lock_for "cpp/thread/shared timed mutex/try lock for"), [`try_lock_until()`](shared_timed_mutex/try_lock_until "cpp/thread/shared timed mutex/try lock until"), [`try_lock_shared_for()`](shared_timed_mutex/try_lock_shared_for "cpp/thread/shared timed mutex/try lock shared for"), [`try_lock_shared_until()`](shared_timed_mutex/try_lock_shared_until "cpp/thread/shared timed mutex/try lock shared until") member functions. The `shared_timed_mutex` class satisfies all requirements of [SharedTimedMutex](../named_req/sharedtimedmutex "cpp/named req/SharedTimedMutex") and [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member functions | | | | --- | --- | | [(constructor)](shared_timed_mutex/shared_timed_mutex "cpp/thread/shared timed mutex/shared timed mutex") | constructs the mutex (public member function) | | [(destructor)](shared_timed_mutex/~shared_timed_mutex "cpp/thread/shared timed mutex/~shared timed mutex") | destroys the mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Exclusive locking | | [lock](shared_timed_mutex/lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](shared_timed_mutex/try_lock "cpp/thread/shared timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](shared_timed_mutex/try_lock_for "cpp/thread/shared timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](shared_timed_mutex/try_lock_until "cpp/thread/shared timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](shared_timed_mutex/unlock "cpp/thread/shared timed mutex/unlock") | unlocks the mutex (public member function) | | Shared locking | | [lock\_shared](shared_timed_mutex/lock_shared "cpp/thread/shared timed mutex/lock shared") | locks the mutex for shared ownership, blocks if the mutex is not available (public member function) | | [try\_lock\_shared](shared_timed_mutex/try_lock_shared "cpp/thread/shared timed mutex/try lock shared") | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) | | [try\_lock\_shared\_for](shared_timed_mutex/try_lock_shared_for "cpp/thread/shared timed mutex/try lock shared for") | tries to lock the mutex for shared ownership, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_shared\_until](shared_timed_mutex/try_lock_shared_until "cpp/thread/shared timed mutex/try lock shared until") | tries to lock the mutex for shared ownership, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock\_shared](shared_timed_mutex/unlock_shared "cpp/thread/shared timed mutex/unlock shared") | unlocks the mutex (shared ownership) (public member function) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_shared_timed_mutex`](../feature_test#Library_features "cpp/feature test") | ### Example A copy assignment operator for a class that holds resources that can handle multiple readers, but only one writer. ``` #include <mutex> #include <shared_mutex> class R { mutable std::shared_timed_mutex mut; /* data */ public: R& operator=(const R& other) { // requires exclusive ownership to write to *this std::unique_lock<std::shared_timed_mutex> lhs(mut, std::defer_lock); // requires shared ownership to read from other std::shared_lock<std::shared_timed_mutex> rhs(other.mut, std::defer_lock); std::lock(lhs, rhs); /* assign data */ return *this; } }; int main() { R r; } ``` cpp std::future_error std::future\_error ================== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` class future_error; ``` | | (since C++11) | The class `std::future_error` defines an exception object that is thrown on failure by the functions in the thread library that deal with asynchronous execution and shared states (`[std::future](future "cpp/thread/future")`, `[std::promise](promise "cpp/thread/promise")`, etc). Similar to `[std::system\_error](../error/system_error "cpp/error/system error")`, this exception carries an error code compatible with `[std::error\_code](../error/error_code "cpp/error/error code")`. ![std-future error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | [(constructor)](future_error/future_error "cpp/thread/future error/future error") | creates a `std::future_error` object (public member function) | | [operator=](future_error/operator= "cpp/thread/future error/operator=") | replaces the `std::future_error` object (public member function) | | [code](future_error/code "cpp/thread/future error/code") | returns the error code (public member function) | | [what](future_error/what "cpp/thread/future error/what") | returns the explanatory string specific to the error code (public member function) | Inherited from [std::logic\_error](../error/logic_error "cpp/error/logic error") ---------------------------------------------------------------------------------- Inherited from [std::exception](../error/exception "cpp/error/exception") --------------------------------------------------------------------------- ### Member functions | | | | --- | --- | | [(destructor)](../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ``` #include <future> #include <iostream> int main() { std::future<int> empty; try { int n = empty.get(); // The behavior is undefined, but // some implementations throw std::future_error } catch (const std::future_error& e) { std::cout << "Caught a future_error with code \"" << e.code() << "\"\nMessage: \"" << e.what() << "\"\n"; } } ``` Possible output: ``` Caught a future_error with code "future:3" Message: "No associated state" ``` ### See also | | | | --- | --- | | [future\_errc](future_errc "cpp/thread/future errc") (C++11) | identifies the future error codes (enum) | cpp std::mutex std::mutex ========== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` class mutex; ``` | | (since C++11) | The `mutex` class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. `mutex` offers exclusive, non-recursive ownership semantics: * A calling thread *owns* a `mutex` from the time that it successfully calls either [`lock`](mutex/lock "cpp/thread/mutex/lock") or [`try_lock`](mutex/try_lock "cpp/thread/mutex/try lock") until it calls [`unlock`](mutex/unlock "cpp/thread/mutex/unlock"). * When a thread owns a `mutex`, all other threads will block (for calls to [`lock`](mutex/lock "cpp/thread/mutex/lock")) or receive a `false` return value (for [`try_lock`](mutex/try_lock "cpp/thread/mutex/try lock")) if they attempt to claim ownership of the `mutex`. * A calling thread must not own the `mutex` prior to calling [`lock`](mutex/lock "cpp/thread/mutex/lock") or [`try_lock`](mutex/try_lock "cpp/thread/mutex/try lock"). The behavior of a program is undefined if a `mutex` is destroyed while still owned by any threads, or a thread terminates while owning a `mutex`. The `mutex` class satisfies all requirements of [Mutex](../named_req/mutex "cpp/named req/Mutex") and [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). `std::mutex` is neither copyable nor movable. ### Member types | Member type | Definition | | --- | --- | | `native_handle_type`(not always present) | *implementation-defined* | ### Member functions | | | | --- | --- | | [(constructor)](mutex/mutex "cpp/thread/mutex/mutex") | constructs the mutex (public member function) | | [(destructor)](mutex/~mutex "cpp/thread/mutex/~mutex") | destroys the mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Locking | | [lock](mutex/lock "cpp/thread/mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](mutex/try_lock "cpp/thread/mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](mutex/unlock "cpp/thread/mutex/unlock") | unlocks the mutex (public member function) | | Native handle | | [native\_handle](mutex/native_handle "cpp/thread/mutex/native handle") | returns the underlying implementation-defined native handle object (public member function) | ### Notes `std::mutex` is usually not accessed directly: `[std::unique\_lock](unique_lock "cpp/thread/unique lock")`, `[std::lock\_guard](lock_guard "cpp/thread/lock guard")`, or [`std::scoped_lock`](scoped_lock "cpp/thread/scoped lock") (since C++17) manage locking in a more exception-safe manner. ### Example This example shows how a `mutex` can be used to protect an `[std::map](../container/map "cpp/container/map")` shared between two threads. ``` #include <iostream> #include <map> #include <string> #include <chrono> #include <thread> #include <mutex> std::map<std::string, std::string> g_pages; std::mutex g_pages_mutex; void save_page(const std::string &url) { // simulate a long page fetch std::this_thread::sleep_for(std::chrono::seconds(2)); std::string result = "fake content"; std::lock_guard<std::mutex> guard(g_pages_mutex); g_pages[url] = result; } int main() { std::thread t1(save_page, "http://foo"); std::thread t2(save_page, "http://bar"); t1.join(); t2.join(); // safe to access g_pages without lock now, as the threads are joined for (const auto &pair : g_pages) { std::cout << pair.first << " => " << pair.second << '\n'; } } ``` Output: ``` http://bar => fake content http://foo => fake content ``` ### See also | | | | --- | --- | | [recursive\_mutex](recursive_mutex "cpp/thread/recursive mutex") (C++11) | provides mutual exclusion facility which can be locked recursively by the same thread (class) | | [lock\_guard](lock_guard "cpp/thread/lock guard") (C++11) | implements a strictly scope-based mutex ownership wrapper (class template) | | [unique\_lock](unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | | [scoped\_lock](scoped_lock "cpp/thread/scoped lock") (C++17) | deadlock-avoiding RAII wrapper for multiple mutexes (class template) | | [condition\_variable](condition_variable "cpp/thread/condition variable") (C++11) | provides a condition variable associated with a `[std::unique\_lock](unique_lock "cpp/thread/unique lock")` (class) | cpp std::defer_lock_t, std::try_to_lock_t, std::adopt_lock_t std::defer\_lock\_t, std::try\_to\_lock\_t, std::adopt\_lock\_t =============================================================== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` struct defer_lock_t { explicit defer_lock_t() = default; }; struct try_to_lock_t { explicit try_to_lock_t() = default; }; struct adopt_lock_t { explicit adopt_lock_t() = default; }; ``` | | (since C++11) | `std::defer_lock_t`, `std::try_to_lock_t` and `std::adopt_lock_t` are empty class tag types used to specify locking strategy for `[std::lock\_guard](lock_guard "cpp/thread/lock guard")`, `std::scoped_lock`, `[std::unique\_lock](unique_lock "cpp/thread/unique lock")`, and `[std::shared\_lock](shared_lock "cpp/thread/shared lock")`. | Type | Effect(s) | | --- | --- | | `defer_lock_t` | do not acquire ownership of the mutex | | `try_to_lock_t` | try to acquire ownership of the mutex without blocking | | `adopt_lock_t` | assume the calling thread already has ownership of the mutex | ### Example ``` #include <mutex> #include <thread> #include <iostream> struct bank_account { explicit bank_account(int balance) : balance{balance} {} int balance; std::mutex m; }; void transfer(bank_account &from, bank_account &to, int amount) { if(&from == &to) return; // avoid deadlock in case of self transfer // lock both mutexes without deadlock std::lock(from.m, to.m); // make sure both already-locked mutexes are unlocked at the end of scope std::lock_guard lock1{from.m, std::adopt_lock}; std::lock_guard lock2{to.m, std::adopt_lock}; // equivalent approach: // std::unique_lock<std::mutex> lock1{from.m, std::defer_lock}; // std::unique_lock<std::mutex> lock2{to.m, std::defer_lock}; // std::lock(lock1, lock2); from.balance -= amount; to.balance += amount; } int main() { bank_account my_account{100}; bank_account your_account{50}; std::thread t1{transfer, std::ref(my_account), std::ref(your_account), 10}; std::thread t2{transfer, std::ref(your_account), std::ref(my_account), 5}; t1.join(); t2.join(); std::cout << "my_account.balance = " << my_account.balance << "\n" "your_account.balance = " << your_account.balance << '\n'; } ``` Output: ``` my_account.balance = 95 your_account.balance = 55 ``` ### 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 2510](https://cplusplus.github.io/LWG/issue2510) | C++11 | the default constructors were non-explicit, which could lead to ambiguity | made explicit | ### See also | | | | --- | --- | | [defer\_locktry\_to\_lockadopt\_lock](lock_tag "cpp/thread/lock tag") (C++11)(C++11)(C++11) | tag constants used to specify locking strategy (constant) | | [(constructor)](lock_guard/lock_guard "cpp/thread/lock guard/lock guard") | constructs a lock\_guard, optionally locking the given mutex (public member function of `std::lock_guard<Mutex>`) | | [(constructor)](unique_lock/unique_lock "cpp/thread/unique lock/unique lock") | constructs a `unique_lock`, optionally locking (i.e., taking ownership of) the supplied mutex (public member function of `std::unique_lock<Mutex>`) |
programming_docs
cpp std::shared_mutex std::shared\_mutex ================== | Defined in header `[<shared\_mutex>](../header/shared_mutex "cpp/header/shared mutex")` | | | | --- | --- | --- | | ``` class shared_mutex; ``` | | (since C++17) | The `shared_mutex` class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In contrast to other mutex types which facilitate exclusive access, a shared\_mutex has two levels of access: * *shared* - several threads can share ownership of the same mutex. * *exclusive* - only one thread can own the mutex. If one thread has acquired the *exclusive* lock (through `[lock](shared_mutex/lock "cpp/thread/shared mutex/lock")`, `[try\_lock](shared_mutex/try_lock "cpp/thread/shared mutex/try lock")`), no other threads can acquire the lock (including the *shared*). If one thread has acquired the *shared* lock (through `[lock\_shared](shared_mutex/lock_shared "cpp/thread/shared mutex/lock shared")`, `[try\_lock\_shared](shared_mutex/try_lock_shared "cpp/thread/shared mutex/try lock shared")`), no other thread can acquire the *exclusive* lock, but can acquire the *shared* lock. Only when the *exclusive* lock has not been acquired by any thread, the *shared* lock can be acquired by multiple threads. Within one thread, only one lock (*shared* or *exclusive*) can be acquired at the same time. Shared mutexes are especially useful when shared data can be safely read by any number of threads simultaneously, but a thread may only write the same data when no other thread is reading or writing at the same time. The `shared_mutex` class satisfies all requirements of [SharedMutex](../named_req/sharedmutex "cpp/named req/SharedMutex") and [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member types | Member type | Definition | | --- | --- | | `native_handle_type`(not always present) | *implementation-defined* | ### Member functions | | | | --- | --- | | [(constructor)](shared_mutex/shared_mutex "cpp/thread/shared mutex/shared mutex") | constructs the mutex (public member function) | | [(destructor)](shared_mutex/~shared_mutex "cpp/thread/shared mutex/~shared mutex") | destroys the mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Exclusive locking | | [lock](shared_mutex/lock "cpp/thread/shared mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](shared_mutex/try_lock "cpp/thread/shared mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](shared_mutex/unlock "cpp/thread/shared mutex/unlock") | unlocks the mutex (public member function) | | Shared locking | | [lock\_shared](shared_mutex/lock_shared "cpp/thread/shared mutex/lock shared") | locks the mutex for shared ownership, blocks if the mutex is not available (public member function) | | [try\_lock\_shared](shared_mutex/try_lock_shared "cpp/thread/shared mutex/try lock shared") | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) | | [unlock\_shared](shared_mutex/unlock_shared "cpp/thread/shared mutex/unlock shared") | unlocks the mutex (shared ownership) (public member function) | | Native handle | | [native\_handle](shared_mutex/native_handle "cpp/thread/shared mutex/native handle") | returns the underlying implementation-defined native handle object (public member function) | ### Example ``` #include <iostream> #include <mutex> #include <shared_mutex> #include <thread> class ThreadSafeCounter { public: ThreadSafeCounter() = default; // Multiple threads/readers can read the counter's value at the same time. unsigned int get() const { std::shared_lock lock(mutex_); return value_; } // Only one thread/writer can increment/write the counter's value. void increment() { std::unique_lock lock(mutex_); ++value_; } // Only one thread/writer can reset/write the counter's value. void reset() { std::unique_lock lock(mutex_); value_ = 0; } private: mutable std::shared_mutex mutex_; unsigned int value_ = 0; }; int main() { ThreadSafeCounter counter; auto increment_and_print = [&counter]() { for (int i = 0; i < 3; i++) { counter.increment(); std::cout << std::this_thread::get_id() << ' ' << counter.get() << '\n'; // Note: Writing to std::cout actually needs to be synchronized as well // by another std::mutex. This has been omitted to keep the example small. } }; std::thread thread1(increment_and_print); std::thread thread2(increment_and_print); thread1.join(); thread2.join(); } // Explanation: The output below was generated on a single-core machine. When // thread1 starts, it enters the loop for the first time and calls increment() // followed by get(). However, before it can print the returned value to // std::cout, the scheduler puts thread1 to sleep and wakes up thread2, which // obviously has time enough to run all three loop iterations at once. Back to // thread1, still in the first loop iteration, it finally prints its local copy // of the counter's value, which is 1, to std::cout and then runs the remaining // two loop iterations. On a multi-core machine, none of the threads is put to // sleep and the output is more likely to be in ascending order. ``` Possible output: ``` 123084176803584 2 123084176803584 3 123084176803584 4 123084185655040 1 123084185655040 5 123084185655040 6 ``` ### See also | | | | --- | --- | | [shared\_timed\_mutex](shared_timed_mutex "cpp/thread/shared timed mutex") (C++14) | provides shared mutual exclusion facility and implements locking with a timeout (class) | | [shared\_lock](shared_lock "cpp/thread/shared lock") (C++14) | implements movable shared mutex ownership wrapper (class template) | | [unique\_lock](unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | cpp std::lock_guard std::lock\_guard ================ | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` template< class Mutex > class lock_guard; ``` | | (since C++11) | The class `lock_guard` is a mutex wrapper that provides a convenient [RAII-style](../language/raii "cpp/language/raii") mechanism for owning a mutex for the duration of a scoped block. When a `lock_guard` object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the `lock_guard` object was created, the `lock_guard` is destructed and the mutex is released. The `lock_guard` class is non-copyable. ### Template parameters | | | | | --- | --- | --- | | Mutex | - | the type of the mutex to lock. The type must meet the [BasicLockable](../named_req/basiclockable "cpp/named req/BasicLockable") requirements | ### Member types | Member type | Definition | | --- | --- | | `mutex_type` | Mutex | ### Member functions | | | | --- | --- | | [(constructor)](lock_guard/lock_guard "cpp/thread/lock guard/lock guard") | constructs a lock\_guard, optionally locking the given mutex (public member function) | | [(destructor)](lock_guard/~lock_guard "cpp/thread/lock guard/~lock guard") | destructs the lock\_guard object, unlocks the underlying mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | | | | --- | --- | | Notes [`std::scoped_lock`](scoped_lock "cpp/thread/scoped lock") offers a replacement for `lock_guard` that provides the ability to lock multiple mutexes using a deadlock avoidance algorithm. | (since C++17) | ### Example ``` #include <thread> #include <mutex> #include <iostream> int g_i = 0; std::mutex g_i_mutex; // protects g_i void safe_increment() { const std::lock_guard<std::mutex> lock(g_i_mutex); ++g_i; std::cout << "g_i: " << g_i << "; in thread #" << std::this_thread::get_id() << '\n'; // g_i_mutex is automatically released when lock // goes out of scope } int main() { std::cout << "g_i: " << g_i << "; in main()\n"; std::thread t1(safe_increment); std::thread t2(safe_increment); t1.join(); t2.join(); std::cout << "g_i: " << g_i << "; in main()\n"; } ``` Possible output: ``` g_i: 0; in main() g_i: 1; in thread #140487981209344 g_i: 2; in thread #140487972816640 g_i: 2; in main() ``` ### 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 2981](https://cplusplus.github.io/LWG/issue2981) | C++17 | redundant deduction guide from `lock_guard<Mutex>` was provided | removed | ### See also | | | | --- | --- | | [unique\_lock](unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | | [scoped\_lock](scoped_lock "cpp/thread/scoped lock") (C++17) | deadlock-avoiding RAII wrapper for multiple mutexes (class template) | cpp std::scoped_lock std::scoped\_lock ================= | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` template< class... MutexTypes > class scoped_lock; ``` | | (since C++17) | The class `scoped_lock` is a mutex wrapper that provides a convenient [RAII-style](https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization "enwiki:Resource Acquisition Is Initialization") mechanism for owning one or more mutexes for the duration of a scoped block. When a `scoped_lock` object is created, it attempts to take ownership of the mutexes it is given. When control leaves the scope in which the `scoped_lock` object was created, the `scoped_lock` is destructed and the mutexes are released. If several mutexes are given, deadlock avoidance algorithm is used as if by `[std::lock](lock "cpp/thread/lock")`. The `scoped_lock` class is non-copyable. ### Template parameters | | | | | --- | --- | --- | | MutexTypes | - | the types of the mutexes to lock. The types must meet the [Lockable](../named_req/lockable "cpp/named req/Lockable") requirements unless `sizeof...(MutexTypes)==1`, in which case the only type must meet [BasicLockable](../named_req/basiclockable "cpp/named req/BasicLockable") | ### Member types | Member type | Definition | | --- | --- | | `mutex_type` (if `sizeof...(MutexTypes)==1`) | Mutex, the sole type in `MutexTypes...` | ### Member functions | | | | --- | --- | | [(constructor)](scoped_lock/scoped_lock "cpp/thread/scoped lock/scoped lock") | constructs a scoped\_lock, optionally locking the given mutexes (public member function) | | [(destructor)](scoped_lock/~scoped_lock "cpp/thread/scoped lock/~scoped lock") | destructs the scoped\_lock object, unlocks the underlying mutexes (public member function) | | operator= [deleted] | not copy-assignable (public member function) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_scoped_lock`](../feature_test#Library_features "cpp/feature test") | ### Example The following example uses `std::scoped_lock` to lock pairs of mutexes without deadlock and is RAII-style. ``` #include <mutex> #include <thread> #include <iostream> #include <vector> #include <functional> #include <chrono> #include <string> struct Employee { Employee(std::string id) : id(id) {} std::string id; std::vector<std::string> lunch_partners; std::mutex m; std::string output() const { std::string ret = "Employee " + id + " has lunch partners: "; for( const auto& partner : lunch_partners ) ret += partner + " "; return ret; } }; void send_mail(Employee &, Employee &) { // simulate a time-consuming messaging operation std::this_thread::sleep_for(std::chrono::seconds(1)); } void assign_lunch_partner(Employee &e1, Employee &e2) { static std::mutex io_mutex; { std::lock_guard<std::mutex> lk(io_mutex); std::cout << e1.id << " and " << e2.id << " are waiting for locks" << std::endl; } { // use std::scoped_lock to acquire two locks without worrying about // other calls to assign_lunch_partner deadlocking us // and it also provides a convenient RAII-style mechanism std::scoped_lock lock(e1.m, e2.m); // Equivalent code 1 (using std::lock and std::lock_guard) // std::lock(e1.m, e2.m); // std::lock_guard<std::mutex> lk1(e1.m, std::adopt_lock); // std::lock_guard<std::mutex> lk2(e2.m, std::adopt_lock); // Equivalent code 2 (if unique_locks are needed, e.g. for condition variables) // std::unique_lock<std::mutex> lk1(e1.m, std::defer_lock); // std::unique_lock<std::mutex> lk2(e2.m, std::defer_lock); // std::lock(lk1, lk2); { std::lock_guard<std::mutex> lk(io_mutex); std::cout << e1.id << " and " << e2.id << " got locks" << std::endl; } e1.lunch_partners.push_back(e2.id); e2.lunch_partners.push_back(e1.id); } send_mail(e1, e2); send_mail(e2, e1); } int main() { Employee alice("alice"), bob("bob"), christina("christina"), dave("dave"); // assign in parallel threads because mailing users about lunch assignments // takes a long time std::vector<std::thread> threads; threads.emplace_back(assign_lunch_partner, std::ref(alice), std::ref(bob)); threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(bob)); threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(alice)); threads.emplace_back(assign_lunch_partner, std::ref(dave), std::ref(bob)); for (auto &thread : threads) thread.join(); std::cout << alice.output() << '\n' << bob.output() << '\n' << christina.output() << '\n' << dave.output() << '\n'; } ``` Possible output: ``` alice and bob are waiting for locks alice and bob got locks christina and bob are waiting for locks christina and alice are waiting for locks dave and bob are waiting for locks dave and bob got locks christina and alice got locks christina and bob got locks Employee alice has lunch partners: bob christina Employee bob has lunch partners: alice dave christina Employee christina has lunch partners: alice bob Employee dave has lunch partners: bob ``` ### 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 2981](https://cplusplus.github.io/LWG/issue2981) | C++17 | redundant deduction guide from `scoped_lock<MutexTypes...>` was provided | removed | ### See also | | | | --- | --- | | [unique\_lock](unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | | | | | --- | --- | | [lock\_guard](lock_guard "cpp/thread/lock guard") (C++11) | implements a strictly scope-based mutex ownership wrapper (class template) | cpp std::notify_all_at_thread_exit std::notify\_all\_at\_thread\_exit ================================== | Defined in header `[<condition\_variable>](../header/condition_variable "cpp/header/condition variable")` | | | | --- | --- | --- | | ``` void notify_all_at_thread_exit( std::condition_variable& cond, std::unique_lock<std::mutex> lk ); ``` | | (since C++11) | `notify_all_at_thread_exit` provides a mechanism to notify other threads that a given thread has completely finished, including destroying all [thread\_local](../keyword/thread_local "cpp/keyword/thread local") objects. It operates as follows: * Ownership of the previously acquired lock `lk` is transferred to internal storage. * The execution environment is modified such that when the current thread exits, the condition variable `cond` is notified as if by: `lk.unlock(); cond.notify_all();` The implied `lk.unlock` is *sequenced after* (as defined in `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the destruction of all objects with [thread local storage duration](../keyword/thread_local "cpp/keyword/thread local") associated with the current thread. An equivalent effect may be achieved with the facilities provided by `[std::promise](promise "cpp/thread/promise")` or `[std::packaged\_task](packaged_task "cpp/thread/packaged task")`. ### Notes Calling this function if `lock.mutex()` is not locked by the current thread is undefined behavior. Calling this function if `lock.mutex()` is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior. The supplied lock `lk` is held until the thread exits. Once this function has been called, no more threads may acquire the same lock in order to wait on `cond`. If some thread is waiting on this condition variable, it should not attempt to release and reacquire the lock when it wakes up spuriously. In typical use cases, this function is the last thing called by a detached thread. ### Parameters | | | | | --- | --- | --- | | cond | - | the condition variable to notify at thread exit | | lk | - | the lock associated with the condition variable `cond` | ### Return value (none). ### Example This partial code fragment illustrates how `notify_all_at_thread_exit` can be used to avoid accessing data that depends on thread locals while those thread locals are in the process of being destructed: ``` #include <mutex> #include <thread> #include <condition_variable> #include <cassert> #include <string> std::mutex m; std::condition_variable cv; bool ready = false; std::string result; // some arbitrary type void thread_func() { thread_local std::string thread_local_data = "42"; std::unique_lock<std::mutex> lk(m); // assign a value to result using thread_local data result = thread_local_data; ready = true; std::notify_all_at_thread_exit(cv, std::move(lk)); } // 1. destroy thread_locals; // 2. unlock mutex; // 3. notify cv. int main() { std::thread t(thread_func); t.detach(); // do other work // ... // wait for the detached thread std::unique_lock<std::mutex> lk(m); cv.wait(lk, []{ return ready; }); // result is ready and thread_local destructors have finished, no UB assert(result == "42"); } ``` ### See also | | | | --- | --- | | [set\_value\_at\_thread\_exit](promise/set_value_at_thread_exit "cpp/thread/promise/set value at thread exit") | sets the result to specific value while delivering the notification only at thread exit (public member function of `std::promise<R>`) | | [make\_ready\_at\_thread\_exit](packaged_task/make_ready_at_thread_exit "cpp/thread/packaged task/make ready at thread exit") | executes the function ensuring that the result is ready only once the current thread exits (public member function of `std::packaged_task<R(Args...)>`) | cpp std::launch std::launch =========== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` enum class launch : /* unspecified */ { async = /* unspecified */, deferred = /* unspecified */, /* implementation-defined */ }; ``` | | (since C++11) | Specifies the launch policy for a task executed by the `[std::async](async "cpp/thread/async")` function. `std::launch` is an enumeration used as [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType"). The following constants denoting individual bits are defined by the standard library: | Constant | Explanation | | --- | --- | | `std::launch::async` | the task is executed on a different thread, potentially by creating and launching it first | | `std::launch::deferred` | the task is executed on the calling thread the first time its result is requested (lazy evaluation) | In addition, implementations are allowed to: * define additional bits and bitmasks to specify restrictions on task interactions applicable to a subset of launch policies, and * enable those additional bitmasks for the first (default) overload of `[std::async](async "cpp/thread/async")`. ### See also | | | | --- | --- | | [async](async "cpp/thread/async") (C++11) | runs a function asynchronously (potentially in a new thread) and returns a `[std::future](future "cpp/thread/future")` that will hold the result (function template) |
programming_docs
cpp std::promise std::promise ============ | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` template< class R > class promise; ``` | (1) | (since C++11) | | ``` template< class R > class promise<R&>; ``` | (2) | (since C++11) | | ``` template<> class promise<void>; ``` | (3) | (since C++11) | 1) base template 2) non-void specialization, used to communicate objects between threads 3) void specialization, used to communicate stateless events The class template `std::promise` provides a facility to store a value or an exception that is later acquired asynchronously via a `[std::future](future "cpp/thread/future")` object created by the `std::promise` object. Note that the `std::promise` object is meant to be used only once. Each promise is associated with a *shared state*, which contains some state information and a *result* which may be not yet evaluated, evaluated to a value (possibly void) or evaluated to an exception. A promise may do three things with the shared state: * *make ready*: the promise stores the result or the exception in the shared state. Marks the state ready and unblocks any thread waiting on a future associated with the shared state. * *release*: the promise gives up its reference to the shared state. If this was the last such reference, the shared state is destroyed. Unless this was a shared state created by `[std::async](http://en.cppreference.com/w/cpp/thread/async)` which is not yet ready, this operation does not block. * *abandon*: the promise stores the exception of type `[std::future\_error](future_error "cpp/thread/future error")` with error code `[std::future\_errc::broken\_promise](future_errc "cpp/thread/future errc")`, makes the shared state *ready*, and then *releases* it. The promise is the "push" end of the promise-future communication channel: the operation that stores a value in the shared state *synchronizes-with* (as defined in `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the successful return from any function that is waiting on the shared state (such as `[std::future::get](future/get "cpp/thread/future/get")`). Concurrent access to the same shared state may conflict otherwise: for example multiple callers of `[std::shared\_future::get](shared_future/get "cpp/thread/shared future/get")` must either all be read-only or provide external synchronization. ### Member functions | | | | --- | --- | | [(constructor)](promise/promise "cpp/thread/promise/promise") | constructs the promise object (public member function) | | [(destructor)](promise/~promise "cpp/thread/promise/~promise") | destructs the promise object (public member function) | | [operator=](promise/operator= "cpp/thread/promise/operator=") | assigns the shared state (public member function) | | [swap](promise/swap "cpp/thread/promise/swap") | swaps two promise objects (public member function) | | Getting the result | | [get\_future](promise/get_future "cpp/thread/promise/get future") | returns a [`future`](future "cpp/thread/future") associated with the promised result (public member function) | | Setting the result | | [set\_value](promise/set_value "cpp/thread/promise/set value") | sets the result to specific value (public member function) | | [set\_value\_at\_thread\_exit](promise/set_value_at_thread_exit "cpp/thread/promise/set value at thread exit") | sets the result to specific value while delivering the notification only at thread exit (public member function) | | [set\_exception](promise/set_exception "cpp/thread/promise/set exception") | sets the result to indicate an exception (public member function) | | [set\_exception\_at\_thread\_exit](promise/set_exception_at_thread_exit "cpp/thread/promise/set exception at thread exit") | sets the result to indicate an exception while delivering the notification only at thread exit (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::promise)](promise/swap2 "cpp/thread/promise/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::uses\_allocator<std::promise>](promise/uses_allocator "cpp/thread/promise/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | ### Example This example shows how `promise<int>` can be used as signals between threads. ``` #include <vector> #include <thread> #include <future> #include <numeric> #include <iostream> #include <chrono> void accumulate(std::vector<int>::iterator first, std::vector<int>::iterator last, std::promise<int> accumulate_promise) { int sum = std::accumulate(first, last, 0); accumulate_promise.set_value(sum); // Notify future } void do_work(std::promise<void> barrier) { std::this_thread::sleep_for(std::chrono::seconds(1)); barrier.set_value(); } int main() { // Demonstrate using promise<int> to transmit a result between threads. std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 }; std::promise<int> accumulate_promise; std::future<int> accumulate_future = accumulate_promise.get_future(); std::thread work_thread(accumulate, numbers.begin(), numbers.end(), std::move(accumulate_promise)); // future::get() will wait until the future has a valid result and retrieves it. // Calling wait() before get() is not needed //accumulate_future.wait(); // wait for result std::cout << "result=" << accumulate_future.get() << '\n'; work_thread.join(); // wait for thread completion // Demonstrate using promise<void> to signal state between threads. std::promise<void> barrier; std::future<void> barrier_future = barrier.get_future(); std::thread new_work_thread(do_work, std::move(barrier)); barrier_future.wait(); new_work_thread.join(); } ``` Output: ``` result=21 ``` cpp std::this_thread::sleep_until std::this\_thread::sleep\_until =============================== | Defined in header `[<thread>](../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` template< class Clock, class Duration > void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time ); ``` | | (since C++11) | Blocks the execution of the current thread until specified `sleep_time` has been reached. `Clock` must meet the [Clock](../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false` (since C++20). The standard recommends that the clock tied to `sleep_time` be used, in which case adjustments of the clock may be taken into account. Thus, the duration of the block might, but might not, be less or more than `sleep_time - Clock::now()` at the time of the call, depending on the direction of the adjustment and whether it is honored by the implementation. The function also may block for longer than until after `sleep_time` has been reached due to scheduling or resource contention delays. ### Parameters | | | | | --- | --- | --- | | sleep\_time | - | time to block until | ### Return value (none). ### Exceptions Any exception thrown by `Clock` or `Duration` (clocks and durations provided by the standard library never throw). ### Example ``` #include <iostream> #include <chrono> #include <thread> auto now() { return std::chrono::steady_clock::now(); } auto awake_time() { using std::chrono::operator""ms; return now() + 2000ms; } int main() { std::cout << "Hello, waiter...\n" << std::flush; const auto start {now()}; std::this_thread::sleep_until(awake_time()); std::chrono::duration<double, std::milli> elapsed {now() - start}; std::cout << "Waited " << elapsed.count() << " ms\n"; } ``` Output: ``` Hello, waiter... Waited 2000.17 ms ``` ### See also | | | | --- | --- | | [sleep\_for](sleep_for "cpp/thread/sleep for") (C++11) | stops the execution of the current thread for a specified time duration (function) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_sleep "c/thread/thrd sleep") for `thrd_sleep` | cpp std::future_status std::future\_status =================== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` enum class future_status { ready, timeout, deferred }; ``` | | (since C++11) | Specifies state of a future as returned by `wait_for` and `wait_until` functions of `[std::future](future "cpp/thread/future")` and `[std::shared\_future](shared_future "cpp/thread/shared future")`. | Constant | Explanation | | --- | --- | | `deferred` | the shared state contains a deferred function, so the result will be computed only when explicitly requested | | `ready` | the shared state is ready | | `timeout` | the shared state did not become ready before specified timeout duration has passed | ### See also | | | | --- | --- | | [wait\_for](future/wait_for "cpp/thread/future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function of `std::future<T>`) | | [wait\_for](shared_future/wait_for "cpp/thread/shared future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function of `std::shared_future<T>`) | | [wait\_until](future/wait_until "cpp/thread/future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function of `std::future<T>`) | | [wait\_until](shared_future/wait_until "cpp/thread/shared future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function of `std::shared_future<T>`) | cpp std::future_errc std::future\_errc ================= | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` enum class future_errc { broken_promise = /* implementation-defined */, future_already_retrieved = /* implementation-defined */, promise_already_satisfied = /* implementation-defined */, no_state = /* implementation-defined */ }; ``` | | (since C++11) | The scoped enumeration `std::future_errc` defines the error codes reported by `[std::future](future "cpp/thread/future")` and related classes in `[std::future\_error](future_error "cpp/thread/future error")` exception objects. Only four error codes are required, although the implementation may define additional error codes. Because the appropriate specialization of `[std::is\_error\_code\_enum](../error/error_code/is_error_code_enum "cpp/error/error code/is error code enum")` is provided, values of type `std::future_errc` are implicitly convertible to `[std::error\_code](../error/error_code "cpp/error/error code")`. All error codes are distinct and non-zero. ### Member constants | Constant | Explanation | | --- | --- | | `broken_promise` | the asynchronous task abandoned its shared state | | `future_already_retrieved` | the contents of shared state were already accessed through `[std::future](future "cpp/thread/future")` | | `promise_already_satisfied` | attempt to store a value in the shared state twice | | `no_state` | attempt to access `[std::promise](promise "cpp/thread/promise")` or `[std::future](future "cpp/thread/future")` without an associated shared state | ### Non-member functions | | | | --- | --- | | [make\_error\_code(std::future\_errc)](future_errc/make_error_code "cpp/thread/future errc/make error code") (C++11) | constructs a future error code (function) | | [make\_error\_condition(std::future\_errc)](future_errc/make_error_condition "cpp/thread/future errc/make error condition") (C++11) | constructs a future error\_condition (function) | ### Helper classes | | | | --- | --- | | [is\_error\_code\_enum<std::future\_errc>](future_errc/is_error_code_enum "cpp/thread/future errc/is error code enum") (C++11) | extends the type trait `[std::is\_error\_code\_enum](../error/error_code/is_error_code_enum "cpp/error/error code/is error code enum")` to identify future error codes (class template) | ### 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 2056](https://cplusplus.github.io/LWG/issue2056) | C++11 | `broken_promise` was specified to be zero which is conventionally used to mean "no error" | specified to be non-zero | ### See also | | | | --- | --- | | [error\_code](../error/error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [error\_condition](../error/error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | cpp std::timed_mutex std::timed\_mutex ================= | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` class timed_mutex; ``` | | (since C++11) | The `timed_mutex` class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In a manner similar to [`mutex`](mutex "cpp/thread/mutex"), `timed_mutex` offers exclusive, non-recursive ownership semantics. In addition, `timed_mutex` provides the ability to attempt to claim ownership of a `timed_mutex` with a timeout via the member functions [`try_lock_for()`](timed_mutex/try_lock_for "cpp/thread/timed mutex/try lock for") and [`try_lock_until()`](timed_mutex/try_lock_until "cpp/thread/timed mutex/try lock until"). The `timed_mutex` class satisfies all requirements of [TimedMutex](../named_req/timedmutex "cpp/named req/TimedMutex") and [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member types | Member type | Definition | | --- | --- | | `native_handle_type`(not always present) | *implementation-defined* | ### Member functions | | | | --- | --- | | [(constructor)](timed_mutex/timed_mutex "cpp/thread/timed mutex/timed mutex") | constructs the mutex (public member function) | | [(destructor)](timed_mutex/~timed_mutex "cpp/thread/timed mutex/~timed mutex") | destroys the mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Locking | | [lock](timed_mutex/lock "cpp/thread/timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](timed_mutex/try_lock "cpp/thread/timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](timed_mutex/try_lock_for "cpp/thread/timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](timed_mutex/try_lock_until "cpp/thread/timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](timed_mutex/unlock "cpp/thread/timed mutex/unlock") | unlocks the mutex (public member function) | | Native handle | | [native\_handle](timed_mutex/native_handle "cpp/thread/timed mutex/native handle") | returns the underlying implementation-defined native handle object (public member function) | cpp std::unique_lock std::unique\_lock ================= | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` template< class Mutex > class unique_lock; ``` | | (since C++11) | The class `unique_lock` is a general-purpose mutex ownership wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables. The class `unique_lock` is movable, but not copyable -- it meets the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") but not of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") or [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). The class `unique_lock` meets the [BasicLockable](../named_req/basiclockable "cpp/named req/BasicLockable") requirements. If **Mutex** meets the [Lockable](../named_req/lockable "cpp/named req/Lockable") requirements, `unique_lock` also meets the [Lockable](../named_req/lockable "cpp/named req/Lockable") requirements (ex.: can be used in `[std::lock](lock "cpp/thread/lock")`); if **Mutex** meets the [TimedLockable](../named_req/timedlockable "cpp/named req/TimedLockable") requirements, `unique_lock` also meets the [TimedLockable](../named_req/timedlockable "cpp/named req/TimedLockable") requirements. ### Template parameters | | | | | --- | --- | --- | | Mutex | - | the type of the mutex to lock. The type must meet the [BasicLockable](../named_req/basiclockable "cpp/named req/BasicLockable") requirements | ### Member types | Type | Definition | | --- | --- | | `mutex_type` | `Mutex` | ### Member functions | | | | --- | --- | | [(constructor)](unique_lock/unique_lock "cpp/thread/unique lock/unique lock") | constructs a `unique_lock`, optionally locking (i.e., taking ownership of) the supplied mutex (public member function) | | [(destructor)](unique_lock/~unique_lock "cpp/thread/unique lock/~unique lock") | unlocks (i.e., releases ownership of) the associated mutex, if owned (public member function) | | [operator=](unique_lock/operator= "cpp/thread/unique lock/operator=") | unlocks (i.e., releases ownership of) the mutex, if owned, and acquires ownership of another (public member function) | | Locking | | [lock](unique_lock/lock "cpp/thread/unique lock/lock") | locks (i.e., takes ownership of) the associated mutex (public member function) | | [try\_lock](unique_lock/try_lock "cpp/thread/unique lock/try lock") | tries to lock (i.e., takes ownership of) the associated mutex without blocking (public member function) | | [try\_lock\_for](unique_lock/try_lock_for "cpp/thread/unique lock/try lock for") | attempts to lock (i.e., takes ownership of) the associated [TimedLockable](../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable for the specified time duration (public member function) | | [try\_lock\_until](unique_lock/try_lock_until "cpp/thread/unique lock/try lock until") | tries to lock (i.e., takes ownership of) the associated [TimedLockable](../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable until specified time point has been reached (public member function) | | [unlock](unique_lock/unlock "cpp/thread/unique lock/unlock") | unlocks (i.e., releases ownership of) the associated mutex (public member function) | | Modifiers | | [swap](unique_lock/swap "cpp/thread/unique lock/swap") | swaps state with another `std::unique_lock` (public member function) | | [release](unique_lock/release "cpp/thread/unique lock/release") | disassociates the associated mutex without unlocking (i.e., releasing ownership of) it (public member function) | | Observers | | [mutex](unique_lock/mutex "cpp/thread/unique lock/mutex") | returns a pointer to the associated mutex (public member function) | | [owns\_lock](unique_lock/owns_lock "cpp/thread/unique lock/owns lock") | tests whether the lock owns (i.e., has locked) its associated mutex (public member function) | | [operator bool](unique_lock/operator_bool "cpp/thread/unique lock/operator bool") | tests whether the lock owns (i.e., has locked) its associated mutex (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::unique\_lock)](unique_lock/swap2 "cpp/thread/unique lock/swap2") (C++11) | specialization of `[std::swap](../algorithm/swap "cpp/algorithm/swap")` for `unique_lock` (function template) | ### Example ``` #include <mutex> #include <thread> #include <iostream> struct Box { explicit Box(int num) : num_things{num} {} int num_things; std::mutex m; }; void transfer(Box &from, Box &to, int num) { // don't actually take the locks yet std::unique_lock lock1{from.m, std::defer_lock}; std::unique_lock lock2{to.m, std::defer_lock}; // lock both unique_locks without deadlock std::lock(lock1, lock2); from.num_things -= num; to.num_things += num; // 'from.m' and 'to.m' mutexes unlocked in 'unique_lock' dtors } int main() { Box acc1{100}; Box acc2{50}; std::thread t1{transfer, std::ref(acc1), std::ref(acc2), 10}; std::thread t2{transfer, std::ref(acc2), std::ref(acc1), 5}; t1.join(); t2.join(); std::cout << "acc1: " << acc1.num_things << "\n" "acc2: " << acc2.num_things << '\n'; } ``` Output: ``` acc1: 95 acc2: 55 ``` ### 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 2981](https://cplusplus.github.io/LWG/issue2981) | C++17 | redundant deduction guide from `unique_lock<Mutex>` was provided | removed | ### See also | | | | --- | --- | | [lock](lock "cpp/thread/lock") (C++11) | locks specified mutexes, blocks if any are unavailable (function template) | | [lock\_guard](lock_guard "cpp/thread/lock guard") (C++11) | implements a strictly scope-based mutex ownership wrapper (class template) | | [scoped\_lock](scoped_lock "cpp/thread/scoped lock") (C++17) | deadlock-avoiding RAII wrapper for multiple mutexes (class template) | | [mutex](mutex "cpp/thread/mutex") (C++11) | provides basic mutual exclusion facility (class) |
programming_docs
cpp std::barrier std::barrier ============ | Defined in header `[<barrier>](../header/barrier "cpp/header/barrier")` | | | | --- | --- | --- | | ``` template<class CompletionFunction = /* see below */> class barrier; ``` | | (since C++20) | The class template `std::barrier` provides a thread-coordination mechanism that allows at most an expected number of threads to block until the expected number of threads arrive at the barrier. Unlike [`std::latch`](latch "cpp/thread/latch"), barriers are reusable: once the arriving threads are unblocked from a barrier phase's synchronization point, the same barrier can be reused. A barrier object's lifetime consists of a sequence of barrier phases. Each phase defines a *phase synchronization point*. Threads that arrive at the barrier during the phase can block on the phase synchronization point by calling [`wait`](barrier/wait "cpp/thread/barrier/wait"), and will be unblocked when the phase completion step is run. A *barrier phase* consists following steps: 1. The *expected count* is decremented by each call to [`arrive`](barrier/arrive "cpp/thread/barrier/arrive") or [`arrive_and_drop`](barrier/arrive_and_drop "cpp/thread/barrier/arrive and drop"). 2. When the expected count reaches zero, the *phase completion step* is run. The completion step invokes the completion function object, and unblocks all threads blocked on the phase synchronization point. The end of the completion step [strongly happens-before](../atomic/memory_order#Strongly_happens-before "cpp/atomic/memory order") the returns from all calls that were unblocked by the completion step. * For the specialization `std::barrier<>` (using the default template argument), the completion step is run as part of the call to `arrive` or `arrive_and_drop` that caused the expected count to reach zero. * For other specializations, the completion step is run on one of the threads that arrived at the barrier during the phase. And the behavior is undefined if any of the barrier object's member functions other than `wait` are called during the completion step. 3. When the completion step finishes, the expected count is reset to the value specified at construction less the number of calls to `arrive_and_drop` since, and the next *barrier phase* begins. Concurrent invocations of the member functions of `barrier`, except for the destructor, do not introduce data races. ### Template parameters | | | | | --- | --- | --- | | CompletionFunction | - | a function object type | | -`CompletionFunction` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and [Destructible](../named_req/destructible "cpp/named req/Destructible"). `[std::is\_nothrow\_invocable\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<CompletionFunction&>` must be `true`. | The default template argument of `CompletionFunction` is an unspecified function object type that addtionally meets the requirements of [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). Calling an lvalue of it with no arguments has no effects. Every barrier object behaves as if it holds an exposition-only non-static data member `completion_` of type `CompletionFunction` and calls it by `completion_()` on every phase completion step. ### Member types | Name | Definition | | --- | --- | | `arrival_token` | an unspecified object type meeting requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"), [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [Destructible](../named_req/destructible "cpp/named req/Destructible") | ### Member functions | | | | --- | --- | | [(constructor)](barrier/barrier "cpp/thread/barrier/barrier") | constructs a `barrier` (public member function) | | [(destructor)](barrier/~barrier "cpp/thread/barrier/~barrier") | destroys the `barrier` (public member function) | | operator= [deleted] | `barrier` is not assignable (public member function) | | [arrive](barrier/arrive "cpp/thread/barrier/arrive") | arrives at barrier and decrements the expected count (public member function) | | [wait](barrier/wait "cpp/thread/barrier/wait") | blocks at the phase synchronization point until its phase completion step is run (public member function) | | [arrive\_and\_wait](barrier/arrive_and_wait "cpp/thread/barrier/arrive and wait") | arrives at barrier and decrements the expected count by one, then blocks until current phase completes (public member function) | | [arrive\_and\_drop](barrier/arrive_and_drop "cpp/thread/barrier/arrive and drop") | decrements both the initial expected count for subsequent phases and the expected count for current phase by one (public member function) | | Constants | | [max](barrier/max "cpp/thread/barrier/max") [static] | the maximum value of expected count supported by the implementation (public static member function) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_barrier`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <barrier> #include <iostream> #include <string> #include <thread> #include <vector> int main() { const auto workers = { "anil", "busara", "carl" }; auto on_completion = []() noexcept { // locking not needed here static auto phase = "... done\n" "Cleaning up...\n"; std::cout << phase; phase = "... done\n"; }; std::barrier sync_point(std::ssize(workers), on_completion); auto work = [&](std::string name) { std::string product = " " + name + " worked\n"; std::cout << product; // ok, op<< call is atomic sync_point.arrive_and_wait(); product = " " + name + " cleaned\n"; std::cout << product; sync_point.arrive_and_wait(); }; std::cout << "Starting...\n"; std::vector<std::thread> threads; for (auto const& worker : workers) { threads.emplace_back(work, worker); } for (auto& thread : threads) { thread.join(); } } ``` Possible output: ``` Starting... anil worked carl worked busara worked ... done Cleaning up... busara cleaned carl cleaned anil cleaned ... done ``` ### See also | | | | --- | --- | | [latch](latch "cpp/thread/latch") (C++20) | single-use thread barrier (class) | cpp std::jthread std::jthread ============ | Defined in header `[<thread>](../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` class jthread; ``` | | (since C++20) | The class `jthread` represents [a single thread of execution](https://en.wikipedia.org/wiki/Thread_(computing) "enwiki:Thread (computing)"). It has the same general behavior as `[std::thread](thread "cpp/thread/thread")`, except that `jthread` automatically rejoins on destruction, and can be cancelled/stopped in certain situations. Threads begin execution immediately upon construction of the associated thread object (pending any OS scheduling delays), starting at the top-level function provided as a [constructor argument](jthread/jthread "cpp/thread/jthread/jthread"). The return value of the top-level function is ignored and if it terminates by throwing an exception, `[std::terminate](../error/terminate "cpp/error/terminate")` is called. The top-level function may communicate its return value or an exception to the caller via `[std::promise](promise "cpp/thread/promise")` or by modifying shared variables (which may require synchronization, see `[std::mutex](mutex "cpp/thread/mutex")` and `[std::atomic](../atomic/atomic "cpp/atomic/atomic")`). Unlike `[std::thread](thread "cpp/thread/thread")`, the `jthread` logically holds an internal private member of type `std::stop_source`, which maintains a shared stop-state. The `jthread` constructor accepts a function that takes a `[std::stop\_token](stop_token "cpp/thread/stop token")` as its first argument, which will be passed in by the `jthread` from its internal `stop_source`. This allows the function to check if stop has been requested during its execution, and return if it has. `std::jthread` objects may also be in the state that does not represent any thread (after default construction, move from, `detach`, or `join`), and a thread of execution may be not associated with any `jthread` objects (after `detach`). No two `std::jthread` objects may represent the same thread of execution; `std::jthread` is not [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") or [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), although it is [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). ### Member types | Member type | Definition | | --- | --- | | `id` | [`std::thread::id`](thread/id "cpp/thread/thread/id") | | `native_handle_type`(not always present) | [`std::thread::native_handle_type`](thread "cpp/thread/thread") | ### Member functions | | | | --- | --- | | [(constructor)](jthread/jthread "cpp/thread/jthread/jthread") | constructs new jthread object (public member function) | | [(destructor)](jthread/~jthread "cpp/thread/jthread/~jthread") | if joinable() is true, calls request\_stop() and then join(); in either case destructs the jthread object. (public member function) | | [operator=](jthread/operator= "cpp/thread/jthread/operator=") | moves the jthread object (public member function) | | Observers | | [joinable](jthread/joinable "cpp/thread/jthread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | | [get\_id](jthread/get_id "cpp/thread/jthread/get id") | returns the *id* of the thread (public member function) | | [native\_handle](jthread/native_handle "cpp/thread/jthread/native handle") | returns the underlying implementation-defined thread handle (public member function) | | [hardware\_concurrency](jthread/hardware_concurrency "cpp/thread/jthread/hardware concurrency") [static] | returns the number of concurrent threads supported by the implementation (public static member function) | | Operations | | [join](jthread/join "cpp/thread/jthread/join") | waits for the thread to finish its execution (public member function) | | [detach](jthread/detach "cpp/thread/jthread/detach") | permits the thread to execute independently from the thread handle (public member function) | | [swap](jthread/swap "cpp/thread/jthread/swap") | swaps two jthread objects (public member function) | | Stop token handling | | [get\_stop\_source](jthread/get_stop_source "cpp/thread/jthread/get stop source") | returns a stop\_source object associated with the shared stop state of the thread (public member function) | | [get\_stop\_token](jthread/get_stop_token "cpp/thread/jthread/get stop token") | returns a stop\_token associated with the shared stop state of the thread (public member function) | | [request\_stop](jthread/request_stop "cpp/thread/jthread/request stop") | requests execution stop via the shared stop state of the thread (public member function) | ### Non-member functions | | | | --- | --- | | [swap(std::jthread)](jthread/swap2 "cpp/thread/jthread/swap2") (C++20) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_jthread`](../feature_test#Library_features "cpp/feature test") | ### See also | | | | --- | --- | | [thread](thread "cpp/thread/thread") (C++11) | manages a separate thread (class) | cpp std::recursive_timed_mutex std::recursive\_timed\_mutex ============================ | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` class recursive_timed_mutex; ``` | | (since C++11) | The `recursive_timed_mutex` class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In a manner similar to `[std::recursive\_mutex](recursive_mutex "cpp/thread/recursive mutex")`, `recursive_timed_mutex` provides exclusive, recursive ownership semantics. In addition, `recursive_timed_mutex` provides the ability to attempt to claim ownership of a `recursive_timed_mutex` with a timeout via the [`try_lock_for`](recursive_timed_mutex/try_lock_for "cpp/thread/recursive timed mutex/try lock for") and [`try_lock_until`](recursive_timed_mutex/try_lock_until "cpp/thread/recursive timed mutex/try lock until") member functions. The `recursive_timed_mutex` class satisfies all requirements of [TimedMutex](../named_req/timedmutex "cpp/named req/TimedMutex") and [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member types | Member type | Definition | | --- | --- | | `native_handle_type`(not always present) | *implementation-defined* | ### Member functions | | | | --- | --- | | [(constructor)](recursive_timed_mutex/recursive_timed_mutex "cpp/thread/recursive timed mutex/recursive timed mutex") | constructs the mutex (public member function) | | [(destructor)](recursive_timed_mutex/~recursive_timed_mutex "cpp/thread/recursive timed mutex/~recursive timed mutex") | destroys the mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Locking | | [lock](recursive_timed_mutex/lock "cpp/thread/recursive timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](recursive_timed_mutex/try_lock "cpp/thread/recursive timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](recursive_timed_mutex/try_lock_for "cpp/thread/recursive timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](recursive_timed_mutex/try_lock_until "cpp/thread/recursive timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](recursive_timed_mutex/unlock "cpp/thread/recursive timed mutex/unlock") | unlocks the mutex (public member function) | | Native handle | | [native\_handle](recursive_timed_mutex/native_handle "cpp/thread/recursive timed mutex/native handle") | returns the underlying implementation-defined native handle object (public member function) | cpp std::packaged_task std::packaged\_task =================== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` template< class > class packaged_task; //not defined ``` | (1) | (since C++11) | | ``` template< class R, class ...ArgTypes > class packaged_task<R(ArgTypes...)>; ``` | (2) | (since C++11) | The class template `std::packaged_task` wraps any [Callable](../named_req/callable "cpp/named req/Callable") target (function, lambda expression, bind expression, or another function object) so that it can be invoked asynchronously. Its return value or exception thrown is stored in a shared state which can be accessed through `[std::future](future "cpp/thread/future")` objects. | | | | --- | --- | | Just like `[std::function](../utility/functional/function "cpp/utility/functional/function")`, `std::packaged_task` is a polymorphic, allocator-aware container: the stored callable target may be allocated on heap or with a provided allocator. | (until C++17) | ### Member functions | | | | --- | --- | | [(constructor)](packaged_task/packaged_task "cpp/thread/packaged task/packaged task") | constructs the task object (public member function) | | [(destructor)](packaged_task/~packaged_task "cpp/thread/packaged task/~packaged task") | destructs the task object (public member function) | | [operator=](packaged_task/operator= "cpp/thread/packaged task/operator=") | moves the task object (public member function) | | [valid](packaged_task/valid "cpp/thread/packaged task/valid") | checks if the task object has a valid function (public member function) | | [swap](packaged_task/swap "cpp/thread/packaged task/swap") | swaps two task objects (public member function) | | Getting the result | | [get\_future](packaged_task/get_future "cpp/thread/packaged task/get future") | returns a `[std::future](future "cpp/thread/future")` associated with the promised result (public member function) | | Execution | | [operator()](packaged_task/operator() "cpp/thread/packaged task/operator()") | executes the function (public member function) | | [make\_ready\_at\_thread\_exit](packaged_task/make_ready_at_thread_exit "cpp/thread/packaged task/make ready at thread exit") | executes the function ensuring that the result is ready only once the current thread exits (public member function) | | [reset](packaged_task/reset "cpp/thread/packaged task/reset") | resets the state abandoning any stored results of previous executions (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::packaged\_task)](packaged_task/swap2 "cpp/thread/packaged task/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::uses\_allocator<std::packaged\_task>](packaged_task/uses_allocator "cpp/thread/packaged task/uses allocator") (C++11) (until C++17) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | ### [Deduction guides](packaged_task/deduction_guides "cpp/thread/packaged task/deduction guides")(since C++17) ### Example ``` #include <iostream> #include <cmath> #include <thread> #include <future> #include <functional> // unique function to avoid disambiguating the std::pow overload set int f(int x, int y) { return std::pow(x,y); } void task_lambda() { std::packaged_task<int(int,int)> task([](int a, int b) { return std::pow(a, b); }); std::future<int> result = task.get_future(); task(2, 9); std::cout << "task_lambda:\t" << result.get() << '\n'; } void task_bind() { std::packaged_task<int()> task(std::bind(f, 2, 11)); std::future<int> result = task.get_future(); task(); std::cout << "task_bind:\t" << result.get() << '\n'; } void task_thread() { std::packaged_task<int(int,int)> task(f); std::future<int> result = task.get_future(); std::thread task_td(std::move(task), 2, 10); task_td.join(); std::cout << "task_thread:\t" << result.get() << '\n'; } int main() { task_lambda(); task_bind(); task_thread(); } ``` Output: ``` task_lambda: 512 task_bind: 2048 task_thread: 1024 ``` ### 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 3117](https://cplusplus.github.io/LWG/issue3117) | C++17 | deduction guides for `packaged_task` were missing | added | ### See also | | | | --- | --- | | [future](future "cpp/thread/future") (C++11) | waits for a value that is set asynchronously (class template) | cpp std::hardware_destructive_interference_size, std::hardware_constructive_interference_size std::hardware\_destructive\_interference\_size, std::hardware\_constructive\_interference\_size =============================================================================================== | Defined in header `[<new>](../header/new "cpp/header/new")` | | | | --- | --- | --- | | ``` inline constexpr std::size_t hardware_destructive_interference_size = /*implementation-defined*/; ``` | (1) | (since C++17) | | ``` inline constexpr std::size_t hardware_constructive_interference_size = /*implementation-defined*/; ``` | (2) | (since C++17) | 1) Minimum offset between two objects to avoid false sharing. Guaranteed to be at least `alignof([std::max\_align\_t](http://en.cppreference.com/w/cpp/types/max_align_t))` ``` struct keep_apart { alignas(std::hardware_destructive_interference_size) std::atomic<int> cat; alignas(std::hardware_destructive_interference_size) std::atomic<int> dog; }; ``` 2) Maximum size of contiguous memory to promote true sharing. Guaranteed to be at least `alignof([std::max\_align\_t](http://en.cppreference.com/w/cpp/types/max_align_t))` ``` struct together { std::atomic<int> dog; int puppy; }; struct kennel { // Other data members... alignas(sizeof(together)) together pack; // Other data members... }; static_assert(sizeof(together) <= std::hardware_constructive_interference_size); ``` ### Notes These constants provide a portable way to access the L1 data cache line size. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_hardware_interference_size`](../feature_test#Library_features "cpp/feature test") | `201703L` | (C++17) | ### Example The program uses two threads that write (atomically) to the data members of the given global objects. The first object fits in one cache line, which results in "hardware interference". The second object keeps its data members on separate cache lines, so possible "cache synchronization" after thread writes is avoided. ``` #include <atomic> #include <chrono> #include <cstddef> #include <iomanip> #include <iostream> #include <mutex> #include <new> #include <thread> #ifdef __cpp_lib_hardware_interference_size using std::hardware_constructive_interference_size; using std::hardware_destructive_interference_size; #else // 64 bytes on x86-64 │ L1_CACHE_BYTES │ L1_CACHE_SHIFT │ __cacheline_aligned │ ... constexpr std::size_t hardware_constructive_interference_size = 64; constexpr std::size_t hardware_destructive_interference_size = 64; #endif std::mutex cout_mutex; constexpr int max_write_iterations{10'000'000}; // the benchmark time tuning struct alignas(hardware_constructive_interference_size) OneCacheLiner { // occupies one cache line std::atomic_uint64_t x{}; std::atomic_uint64_t y{}; } oneCacheLiner; struct TwoCacheLiner { // occupies two cache lines alignas(hardware_destructive_interference_size) std::atomic_uint64_t x{}; alignas(hardware_destructive_interference_size) std::atomic_uint64_t y{}; } twoCacheLiner; inline auto now() noexcept { return std::chrono::high_resolution_clock::now(); } template<bool xy> void oneCacheLinerThread() { const auto start { now() }; for (uint64_t count{}; count != max_write_iterations; ++count) if constexpr (xy) oneCacheLiner.x.fetch_add(1, std::memory_order_relaxed); else oneCacheLiner.y.fetch_add(1, std::memory_order_relaxed); const std::chrono::duration<double, std::milli> elapsed { now() - start }; std::lock_guard lk{cout_mutex}; std::cout << "oneCacheLinerThread() spent " << elapsed.count() << " ms\n"; if constexpr (xy) oneCacheLiner.x = elapsed.count(); else oneCacheLiner.y = elapsed.count(); } template<bool xy> void twoCacheLinerThread() { const auto start { now() }; for (uint64_t count{}; count != max_write_iterations; ++count) if constexpr (xy) twoCacheLiner.x.fetch_add(1, std::memory_order_relaxed); else twoCacheLiner.y.fetch_add(1, std::memory_order_relaxed); const std::chrono::duration<double, std::milli> elapsed { now() - start }; std::lock_guard lk{cout_mutex}; std::cout << "twoCacheLinerThread() spent " << elapsed.count() << " ms\n"; if constexpr (xy) twoCacheLiner.x = elapsed.count(); else twoCacheLiner.y = elapsed.count(); } int main() { std::cout << "__cpp_lib_hardware_interference_size " # ifdef __cpp_lib_hardware_interference_size " = " << __cpp_lib_hardware_interference_size << '\n'; # else "is not defined, use " << hardware_destructive_interference_size << " as fallback\n"; # endif std::cout << "hardware_destructive_interference_size == " << hardware_destructive_interference_size << '\n' << "hardware_constructive_interference_size == " << hardware_constructive_interference_size << "\n\n"; std::cout << std::fixed << std::setprecision(2) << "sizeof( OneCacheLiner ) == " << sizeof( OneCacheLiner ) << '\n' << "sizeof( TwoCacheLiner ) == " << sizeof( TwoCacheLiner ) << "\n\n"; constexpr int max_runs{4}; int oneCacheLiner_average{0}; for (auto i{0}; i != max_runs; ++i) { std::thread th1{oneCacheLinerThread<0>}; std::thread th2{oneCacheLinerThread<1>}; th1.join(); th2.join(); oneCacheLiner_average += oneCacheLiner.x + oneCacheLiner.y; } std::cout << "Average T1 time: " << (oneCacheLiner_average / max_runs / 2) << " ms\n\n"; int twoCacheLiner_average{0}; for (auto i{0}; i != max_runs; ++i) { std::thread th1{twoCacheLinerThread<0>}; std::thread th2{twoCacheLinerThread<1>}; th1.join(); th2.join(); twoCacheLiner_average += twoCacheLiner.x + twoCacheLiner.y; } std::cout << "Average T2 time: " << (twoCacheLiner_average / max_runs / 2) << " ms\n\n"; std::cout << "Ratio T1/T2:~ " << 1.*oneCacheLiner_average/twoCacheLiner_average << '\n'; } ``` Possible output: ``` __cpp_lib_hardware_interference_size is not defined, use 64 as fallback hardware_destructive_interference_size == 64 hardware_constructive_interference_size == 64 sizeof( OneCacheLiner ) == 64 sizeof( TwoCacheLiner ) == 128 oneCacheLinerThread() spent 634.25 ms oneCacheLinerThread() spent 651.55 ms oneCacheLinerThread() spent 990.23 ms oneCacheLinerThread() spent 1033.94 ms oneCacheLinerThread() spent 838.14 ms oneCacheLinerThread() spent 883.25 ms oneCacheLinerThread() spent 873.02 ms oneCacheLinerThread() spent 914.26 ms Average T1 time: 852 ms twoCacheLinerThread() spent 119.22 ms twoCacheLinerThread() spent 127.91 ms twoCacheLinerThread() spent 114.17 ms twoCacheLinerThread() spent 126.41 ms twoCacheLinerThread() spent 125.17 ms twoCacheLinerThread() spent 126.06 ms twoCacheLinerThread() spent 117.94 ms twoCacheLinerThread() spent 129.03 ms Average T2 time: 122 ms Ratio T1/T2:~ 6.98 ``` ### See also | | | | --- | --- | | [hardware\_concurrency](thread/hardware_concurrency "cpp/thread/thread/hardware concurrency") [static] | returns the number of concurrent threads supported by the implementation (public static member function of `std::thread`) | | [hardware\_concurrency](jthread/hardware_concurrency "cpp/thread/jthread/hardware concurrency") [static] | returns the number of concurrent threads supported by the implementation (public static member function of `std::jthread`) |
programming_docs
cpp std::condition_variable std::condition\_variable ======================== | Defined in header `[<condition\_variable>](../header/condition_variable "cpp/header/condition variable")` | | | | --- | --- | --- | | ``` class condition_variable; ``` | | (since C++11) | The `condition_variable` class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the *condition*), and notifies the `condition_variable`. The thread that intends to modify the shared variable has to. 1. acquire a `std::mutex` (typically via `[std::lock\_guard](lock_guard "cpp/thread/lock guard")`) 2. perform the modification while the lock is held 3. execute `[notify\_one](condition_variable/notify_one "cpp/thread/condition variable/notify one")` or `[notify\_all](condition_variable/notify_all "cpp/thread/condition variable/notify all")` on the `std::condition_variable` (the lock does not need to be held for notification) Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread. Any thread that intends to wait on `std::condition_variable` has to. 1. acquire a `[std::unique\_lock](http://en.cppreference.com/w/cpp/thread/unique_lock)<[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)>`, on the same mutex as used to protect the shared variable 2. either 1. check the condition, in case it was already updated and notified 2. execute `[wait](condition_variable/wait "cpp/thread/condition variable/wait")`, `[wait\_for](condition_variable/wait_for "cpp/thread/condition variable/wait for")`, or `[wait\_until](condition_variable/wait_until "cpp/thread/condition variable/wait until")`. The wait operations atomically release the mutex and suspend the execution of the thread. 3. When the condition variable is notified, a timeout expires, or a [spurious wakeup](https://en.wikipedia.org/wiki/Spurious_wakeup "enwiki:Spurious wakeup") occurs, the thread is awakened, and the mutex is atomically reacquired. The thread should then check the condition and resume waiting if the wake up was spurious. or 1. use the predicated overload of `[wait](condition_variable/wait "cpp/thread/condition variable/wait")`, `[wait\_for](condition_variable/wait_for "cpp/thread/condition variable/wait for")`, and `[wait\_until](condition_variable/wait_until "cpp/thread/condition variable/wait until")`, which takes care of the three steps above `std::condition_variable` works only with `[std::unique\_lock](http://en.cppreference.com/w/cpp/thread/unique_lock)<[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)>`; this restriction allows for maximal efficiency on some platforms. `[std::condition\_variable\_any](condition_variable_any "cpp/thread/condition variable any")` provides a condition variable that works with any [BasicLockable](../named_req/basiclockable "cpp/named req/BasicLockable") object, such as `[std::shared\_lock](shared_lock "cpp/thread/shared lock")`. Condition variables permit concurrent invocation of the `[wait](condition_variable/wait "cpp/thread/condition variable/wait")`, `[wait\_for](condition_variable/wait_for "cpp/thread/condition variable/wait for")`, `[wait\_until](condition_variable/wait_until "cpp/thread/condition variable/wait until")`, `[notify\_one](condition_variable/notify_one "cpp/thread/condition variable/notify one")` and `[notify\_all](condition_variable/notify_all "cpp/thread/condition variable/notify all")` member functions. The class `std::condition_variable` is a [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). It is not [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), or [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). ### Member types | Member type | Definition | | --- | --- | | `native_handle_type` | *implementation-defined* | ### Member functions | | | | --- | --- | | [(constructor)](condition_variable/condition_variable "cpp/thread/condition variable/condition variable") | constructs the object (public member function) | | [(destructor)](condition_variable/~condition_variable "cpp/thread/condition variable/~condition variable") | destructs the object (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Notification | | [notify\_one](condition_variable/notify_one "cpp/thread/condition variable/notify one") | notifies one waiting thread (public member function) | | [notify\_all](condition_variable/notify_all "cpp/thread/condition variable/notify all") | notifies all waiting threads (public member function) | | Waiting | | [wait](condition_variable/wait "cpp/thread/condition variable/wait") | blocks the current thread until the condition variable is woken up (public member function) | | [wait\_for](condition_variable/wait_for "cpp/thread/condition variable/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) | | [wait\_until](condition_variable/wait_until "cpp/thread/condition variable/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) | | Native handle | | [native\_handle](condition_variable/native_handle "cpp/thread/condition variable/native handle") | returns the native handle (public member function) | ### Example `condition_variable` is used in combination with a `[std::mutex](mutex "cpp/thread/mutex")` to facilitate inter-thread communication. ``` #include <iostream> #include <string> #include <thread> #include <mutex> #include <condition_variable> std::mutex m; std::condition_variable cv; std::string data; bool ready = false; bool processed = false; void worker_thread() { // Wait until main() sends data std::unique_lock lk(m); cv.wait(lk, []{return ready;}); // after the wait, we own the lock. std::cout << "Worker thread is processing data\n"; data += " after processing"; // Send data back to main() processed = true; std::cout << "Worker thread signals data processing completed\n"; // Manual unlocking is done before notifying, to avoid waking up // the waiting thread only to block again (see notify_one for details) lk.unlock(); cv.notify_one(); } int main() { std::thread worker(worker_thread); data = "Example data"; // send data to the worker thread { std::lock_guard lk(m); ready = true; std::cout << "main() signals data ready for processing\n"; } cv.notify_one(); // wait for the worker { std::unique_lock lk(m); cv.wait(lk, []{return processed;}); } std::cout << "Back in main(), data = " << data << '\n'; worker.join(); } ``` Output: ``` main() signals data ready for processing Worker thread is processing data Worker thread signals data processing completed Back in main(), data = Example data after processing ``` ### See also | | | | --- | --- | | [condition\_variable\_any](condition_variable_any "cpp/thread/condition variable any") (C++11) | provides a condition variable associated with any lock type (class) | | [mutex](mutex "cpp/thread/mutex") (C++11) | provides basic mutual exclusion facility (class) | | [lock\_guard](lock_guard "cpp/thread/lock guard") (C++11) | implements a strictly scope-based mutex ownership wrapper (class template) | | [unique\_lock](unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | cpp std::defer_lock, std::try_to_lock, std::adopt_lock std::defer\_lock, std::try\_to\_lock, std::adopt\_lock ====================================================== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` constexpr std::defer_lock_t defer_lock {}; ``` | | (since C++11) (until C++17) | | ``` inline constexpr std::defer_lock_t defer_lock {}; ``` | | (since C++17) | | ``` constexpr std::try_to_lock_t try_to_lock {}; ``` | | (since C++11) (until C++17) | | ``` inline constexpr std::try_to_lock_t try_to_lock {}; ``` | | (since C++17) | | ``` constexpr std::adopt_lock_t adopt_lock {}; ``` | | (since C++11) (until C++17) | | ``` inline constexpr std::adopt_lock_t adopt_lock {}; ``` | | (since C++17) | `std::defer_lock`, `std::try_to_lock` and `std::adopt_lock` are instances of empty struct tag types `[std::defer\_lock\_t](lock_tag_t "cpp/thread/lock tag t")`, `[std::try\_to\_lock\_t](lock_tag_t "cpp/thread/lock tag t")` and `[std::adopt\_lock\_t](lock_tag_t "cpp/thread/lock tag t")` respectively. They are used to specify locking strategies for `[std::lock\_guard](lock_guard "cpp/thread/lock guard")`, `[std::unique\_lock](unique_lock "cpp/thread/unique lock")` and `[std::shared\_lock](shared_lock "cpp/thread/shared lock")`. | Type | Effect(s) | | --- | --- | | `defer_lock_t` | do not acquire ownership of the mutex | | `try_to_lock_t` | try to acquire ownership of the mutex without blocking | | `adopt_lock_t` | assume the calling thread already has ownership of the mutex | ### Example ``` #include <mutex> #include <thread> #include <iostream> struct bank_account { explicit bank_account(int balance) : balance{balance} {} int balance; std::mutex m; }; void transfer(bank_account &from, bank_account &to, int amount) { if(&from == &to) return; // avoid deadlock in case of self transfer // lock both mutexes without deadlock std::lock(from.m, to.m); // make sure both already-locked mutexes are unlocked at the end of scope std::lock_guard lock1{from.m, std::adopt_lock}; std::lock_guard lock2{to.m, std::adopt_lock}; // equivalent approach: // std::unique_lock<std::mutex> lock1{from.m, std::defer_lock}; // std::unique_lock<std::mutex> lock2{to.m, std::defer_lock}; // std::lock(lock1, lock2); from.balance -= amount; to.balance += amount; } int main() { bank_account my_account{100}; bank_account your_account{50}; std::thread t1{transfer, std::ref(my_account), std::ref(your_account), 10}; std::thread t2{transfer, std::ref(your_account), std::ref(my_account), 5}; t1.join(); t2.join(); std::cout << "my_account.balance = " << my_account.balance << "\n" "your_account.balance = " << your_account.balance << '\n'; } ``` Output: ``` my_account.balance = 95 your_account.balance = 55 ``` ### See also | | | | --- | --- | | [defer\_lock\_ttry\_to\_lock\_tadopt\_lock\_t](lock_tag_t "cpp/thread/lock tag t") (C++11)(C++11)(C++11) | tag type used to specify locking strategy (class) | | [(constructor)](lock_guard/lock_guard "cpp/thread/lock guard/lock guard") | constructs a lock\_guard, optionally locking the given mutex (public member function of `std::lock_guard<Mutex>`) | | [(constructor)](unique_lock/unique_lock "cpp/thread/unique lock/unique lock") | constructs a `unique_lock`, optionally locking (i.e., taking ownership of) the supplied mutex (public member function of `std::unique_lock<Mutex>`) | cpp std::stop_token std::stop\_token ================ | Defined in header `[<stop\_token>](../header/stop_token "cpp/header/stop token")` | | | | --- | --- | --- | | ``` class stop_token; ``` | | (since C++20) | The `stop_token` class provides the means to check if a stop request has been made or can be made, for its associated [`std::stop_source`](stop_source "cpp/thread/stop source") object. It is essentially a thread-safe "view" of the associated stop-state. The `stop_token` can also be passed to the constructor of [`std::stop_callback`](stop_callback "cpp/thread/stop callback"), such that the callback will be invoked if the `stop_token`'s associated [`std::stop_source`](stop_source "cpp/thread/stop source") is requested to stop. And `stop_token` can be passed to the interruptible waiting functions of `[std::condition\_variable\_any](condition_variable_any "cpp/thread/condition variable any")`, to interrupt the condition variable's wait if stop is requested. ### Member functions | | | | --- | --- | | [(constructor)](stop_token/stop_token "cpp/thread/stop token/stop token") | constructs new stop\_token object (public member function) | | [(destructor)](stop_token/~stop_token "cpp/thread/stop token/~stop token") | destructs the stop\_token object (public member function) | | [operator=](stop_token/operator= "cpp/thread/stop token/operator=") | assigns the stop\_token object (public member function) | | Modifiers | | [swap](stop_token/swap "cpp/thread/stop token/swap") | swaps two stop\_token objects (public member function) | | Observers | | [stop\_requested](stop_token/stop_requested "cpp/thread/stop token/stop requested") | checks whether the associated stop-state has been requested to stop (public member function) | | [stop\_possible](stop_token/stop_possible "cpp/thread/stop token/stop possible") | checks whether associated stop-state can be requested to stop (public member function) | ### Non-member functions | | | | --- | --- | | [operator==](stop_token/operator_cmp "cpp/thread/stop token/operator cmp") | compares two `std::stop_token` objects (function) | | [swap(std::stop\_token)](stop_token/swap2 "cpp/thread/stop token/swap2") (C++20) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | ### Notes A `stop_token` object is not generally constructed independently, but rather retrieved from a `[std::jthread](jthread "cpp/thread/jthread")` or `[std::stop\_source](stop_source "cpp/thread/stop source")`. This makes it share the same associated stop-state as the `[std::jthread](jthread "cpp/thread/jthread")` or `[std::stop\_source](stop_source "cpp/thread/stop source")`. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_jthread`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <thread> #include <iostream> using namespace std::literals::chrono_literals; void f(std::stop_token stop_token, int value) { while (!stop_token.stop_requested()) { std::cout << value++ << ' ' << std::flush; std::this_thread::sleep_for(200ms); } std::cout << std::endl; } int main() { std::jthread thread(f, 5); // prints 5 6 7 8... for approximately 3 seconds std::this_thread::sleep_for(3s); // The destructor of jthread calls request_stop() and join(). } ``` Possible output: ``` 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` cpp std::try_lock std::try\_lock ============== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` template< class Lockable1, class Lockable2, class... LockableN > int try_lock( Lockable1& lock1, Lockable2& lock2, LockableN&... lockn ); ``` | | (since C++11) | Tries to lock each of the given [Lockable](../named_req/lockable "cpp/named req/Lockable") objects `lock1`, `lock2`, `...`, `lockn` by calling `try_lock` in order beginning with the first. If a call to `try_lock` fails, no further call to `try_lock` is performed, `unlock` is called for any locked objects and a `0`-based index of the object that failed to lock is returned. If a call to `try_lock` results in an exception, `unlock` is called for any locked objects before rethrowing. ### Parameters | | | | | --- | --- | --- | | lock1, lock2, ... , lockn | - | the [Lockable](../named_req/lockable "cpp/named req/Lockable") objects to lock | ### Return value `-1` on success, or `0`-based index value of the object that failed to lock. ### Example The following example uses `std::try_lock` to periodically tally and reset counters running in separate threads. ``` #include <mutex> #include <vector> #include <thread> #include <iostream> #include <functional> #include <chrono> int main() { int foo_count = 0; std::mutex foo_count_mutex; int bar_count = 0; std::mutex bar_count_mutex; int overall_count = 0; bool done = false; std::mutex done_mutex; auto increment = [](int &counter, std::mutex &m, const char *desc) { for (int i = 0; i < 10; ++i) { std::unique_lock<std::mutex> lock(m); ++counter; std::cout << desc << ": " << counter << '\n'; lock.unlock(); std::this_thread::sleep_for(std::chrono::seconds(1)); } }; std::thread increment_foo(increment, std::ref(foo_count), std::ref(foo_count_mutex), "foo"); std::thread increment_bar(increment, std::ref(bar_count), std::ref(bar_count_mutex), "bar"); std::thread update_overall([&]() { done_mutex.lock(); while (!done) { done_mutex.unlock(); int result = std::try_lock(foo_count_mutex, bar_count_mutex); if (result == -1) { overall_count += foo_count + bar_count; foo_count = 0; bar_count = 0; std::cout << "overall: " << overall_count << '\n'; foo_count_mutex.unlock(); bar_count_mutex.unlock(); } std::this_thread::sleep_for(std::chrono::seconds(2)); done_mutex.lock(); } done_mutex.unlock(); }); increment_foo.join(); increment_bar.join(); done_mutex.lock(); done = true; done_mutex.unlock(); update_overall.join(); std::cout << "Done processing\n" << "foo: " << foo_count << '\n' << "bar: " << bar_count << '\n' << "overall: " << overall_count << '\n'; } ``` Possible output: ``` bar: 1 foo: 1 foo: 2 bar: 2 foo: 3 overall: 5 bar: 1 foo: 1 bar: 2 foo: 2 bar: 3 overall: 10 bar: 1 foo: 1 bar: 2 foo: 2 overall: 14 bar: 1 foo: 1 bar: 2 overall: 17 foo: 1 bar: 1 foo: 2 overall: 20 Done processing foo: 0 bar: 0 overall: 20 ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/lock") (C++11) | locks specified mutexes, blocks if any are unavailable (function template) | cpp std::counting_semaphore, std::binary_semaphore std::counting\_semaphore, std::binary\_semaphore ================================================ | Defined in header `[<semaphore>](../header/semaphore "cpp/header/semaphore")` | | | | --- | --- | --- | | ``` template<std::ptrdiff_t LeastMaxValue = /* implementation-defined */> class counting_semaphore; ``` | (1) | (since C++20) | | ``` using binary_semaphore = std::counting_semaphore<1>; ``` | (2) | (since C++20) | 1) A `counting_semaphore` is a lightweight synchronization primitive that can control access to a shared resource. Unlike a `[std::mutex](mutex "cpp/thread/mutex")`, a `counting_semaphore` allows more than one concurrent access to the same resource, for at least `LeastMaxValue` concurrent accessors. The program is ill-formed if `LeastMaxValue` is negative. 2) `binary_semaphore` is an alias for specialization of `std::counting_semaphore` with `LeastMaxValue` being `1`. Implementations may implement `binary_semaphore` more efficiently than the default implementation of `std::counting_semaphore`. A `counting_semaphore` contains an internal counter initialized by the constructor. This counter is decremented by calls to `acquire()` and related methods, and is incremented by calls to `release()`. When the counter is zero, `acquire()` blocks until the counter is incremented, but `try_acquire()` does not block; `try_acquire_for()` and `try_acquire_until()` block until the counter is incremented or a timeout is reached. Similar to `[std::condition\_variable::wait()](condition_variable/wait "cpp/thread/condition variable/wait")`, `counting_semaphore`'s `try_acquire()` can spuriously fail. Specializations of `std::counting_semaphore` are not [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), or [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). ### Member functions | | | | --- | --- | | [(constructor)](counting_semaphore/counting_semaphore "cpp/thread/counting semaphore/counting semaphore") | constructs a `counting_semaphore` (public member function) | | [(destructor)](counting_semaphore/~counting_semaphore "cpp/thread/counting semaphore/~counting semaphore") | destructs the `counting_semaphore` (public member function) | | operator= [deleted] | `counting_semaphore` is not assignable (public member function) | | Operations | | [release](counting_semaphore/release "cpp/thread/counting semaphore/release") | increments the internal counter and unblocks acquirers (public member function) | | [acquire](counting_semaphore/acquire "cpp/thread/counting semaphore/acquire") | decrements the internal counter or blocks until it can (public member function) | | [try\_acquire](counting_semaphore/try_acquire "cpp/thread/counting semaphore/try acquire") | tries to decrement the internal counter without blocking (public member function) | | [try\_acquire\_for](counting_semaphore/try_acquire_for "cpp/thread/counting semaphore/try acquire for") | tries to decrement the internal counter, blocking for up to a duration time (public member function) | | [try\_acquire\_until](counting_semaphore/try_acquire_until "cpp/thread/counting semaphore/try acquire until") | tries to decrement the internal counter, blocking until a point in time (public member function) | | Constants | | [max](counting_semaphore/max "cpp/thread/counting semaphore/max") [static] | returns the maximum possible value of the internal counter (public static member function) | ### Notes As its name indicates, the `LeastMaxValue` is the *minimum* max value, not the *actual* max value. Thus `max()` can yield a number larger than `LeastMaxValue`. Unlike `[std::mutex](mutex "cpp/thread/mutex")` a `counting_semaphore` is not tied to threads of execution - acquiring a semaphore can occur on a different thread than releasing the semaphore, for example. All operations on `counting_semaphore` can be performed concurrently and without any relation to specific threads of execution, with the exception of the destructor which cannot be performed concurrently but can be performed on a different thread. Semaphores are also often used for the semantics of signalling/notifying rather than mutual exclusion, by initializing the semaphore with `​0​` and thus blocking the receiver(s) that try to `acquire()`, until the notifier "signals" by invoking `release(n)`. In this respect semaphores can be considered alternatives to `[std::condition\_variable](condition_variable "cpp/thread/condition variable")`s, often with better performance. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_semaphore`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <thread> #include <chrono> #include <semaphore> // global binary semaphore instances // object counts are set to zero // objects are in non-signaled state std::binary_semaphore smphSignalMainToThread{0}, smphSignalThreadToMain{0}; void ThreadProc() { // wait for a signal from the main proc // by attempting to decrement the semaphore smphSignalMainToThread.acquire(); // this call blocks until the semaphore's count // is increased from the main proc std::cout << "[thread] Got the signal\n"; // response message // wait for 3 seconds to imitate some work // being done by the thread using namespace std::literals; std::this_thread::sleep_for(3s); std::cout << "[thread] Send the signal\n"; // message // signal the main proc back smphSignalThreadToMain.release(); } int main() { // create some worker thread std::thread thrWorker(ThreadProc); std::cout << "[main] Send the signal\n"; // message // signal the worker thread to start working // by increasing the semaphore's count smphSignalMainToThread.release(); // wait until the worker thread is done doing the work // by attempting to decrement the semaphore's count smphSignalThreadToMain.acquire(); std::cout << "[main] Got the signal\n"; // response message thrWorker.join(); } ``` Output: ``` [main] Send the signal [thread] Got the signal [thread] Send the signal [main] Got the signal ```
programming_docs
cpp std::latch std::latch ========== | Defined in header `[<latch>](../header/latch "cpp/header/latch")` | | | | --- | --- | --- | | ``` class latch; ``` | | (since C++20) | The `latch` class is a downward counter of type `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` which can be used to synchronize threads. The value of the counter is initialized on creation. Threads may block on the latch until the counter is decremented to zero. There is no possibility to increase or reset the counter, which makes the latch a single-use barrier. Concurrent invocations of the member functions of `std::latch`, except for the destructor, do not introduce data races. Unlike `[std::barrier](barrier "cpp/thread/barrier")`, `std::latch` can be decremented by a participating thread more than once. ### Member functions | | | | --- | --- | | [(constructor)](latch/latch "cpp/thread/latch/latch") | constructs a `latch` (public member function) | | [(destructor)](latch/~latch "cpp/thread/latch/~latch") | destroys the `latch` (public member function) | | operator= [deleted] | `latch` is not assignable (public member function) | | [count\_down](latch/count_down "cpp/thread/latch/count down") | decrements the counter in a non-blocking manner (public member function) | | [try\_wait](latch/try_wait "cpp/thread/latch/try wait") | tests if the internal counter equals zero (public member function) | | [wait](latch/wait "cpp/thread/latch/wait") | blocks until the counter reaches zero (public member function) | | [arrive\_and\_wait](latch/arrive_and_wait "cpp/thread/latch/arrive and wait") | decrements the counter and blocks until it reaches zero (public member function) | | Constants | | [max](latch/max "cpp/thread/latch/max") [static] | the maximum value of counter supported by the implementation (public static member function) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_latch`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <functional> #include <iostream> #include <latch> #include <string> #include <thread> int main() { struct job { const std::string name; std::string product{"not worked"}; std::thread action{}; } jobs[] = {{"annika"}, {"buru"}, {"chuck"}}; std::latch work_done{std::size(jobs)}; std::latch start_clean_up{1}; auto work = [&](job& my_job) { my_job.product = my_job.name + " worked"; work_done.count_down(); start_clean_up.wait(); my_job.product = my_job.name + " cleaned"; }; std::cout << "Work starting... "; for (auto& job : jobs) { job.action = std::thread{work, std::ref(job)}; } work_done.wait(); std::cout << "done:\n"; for (auto const& job : jobs) { std::cout << " " << job.product << '\n'; } std::cout << "Workers cleaning up... "; start_clean_up.count_down(); for (auto& job : jobs) { job.action.join(); } std::cout << "done:\n"; for (auto const& job : jobs) { std::cout << " " << job.product << '\n'; } } ``` Output: ``` Work starting... done: annika worked buru worked chuck worked Workers cleaning up... done: annika cleaned buru cleaned chuck cleaned ``` ### See also | | | | --- | --- | | [barrier](barrier "cpp/thread/barrier") (C++20) | reusable thread barrier (class template) | cpp std::this_thread::get_id std::this\_thread::get\_id ========================== | Defined in header `[<thread>](../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` std::thread::id get_id() noexcept; ``` | | (since C++11) | Returns the *id* of the current thread. ### Parameters (none). ### Return value *id* of the current thread. ### Example ``` #include <iostream> #include <thread> #include <chrono> #include <mutex> std::mutex g_display_mutex; void foo() { std::thread::id this_id = std::this_thread::get_id(); g_display_mutex.lock(); std::cout << "thread " << this_id << " sleeping...\n"; g_display_mutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::thread t1(foo); std::thread t2(foo); t1.join(); t2.join(); } ``` Possible output: ``` thread 0x2384b312 sleeping... thread 0x228a10fc sleeping... ``` ### See also | | | | --- | --- | | [get\_id](thread/get_id "cpp/thread/thread/get id") | returns the *id* of the thread (public member function of `std::thread`) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_current "c/thread/thrd current") for `thrd_current` | cpp std::condition_variable_any std::condition\_variable\_any ============================= | Defined in header `[<condition\_variable>](../header/condition_variable "cpp/header/condition variable")` | | | | --- | --- | --- | | ``` class condition_variable_any; ``` | | (since C++11) | The `condition_variable_any` class is a generalization of `[std::condition\_variable](condition_variable "cpp/thread/condition variable")`. Whereas `[std::condition\_variable](condition_variable "cpp/thread/condition variable")` works only on `[std::unique\_lock](http://en.cppreference.com/w/cpp/thread/unique_lock)<[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)>`, `condition_variable_any` can operate on any lock that meets the [BasicLockable](../named_req/basiclockable "cpp/named req/BasicLockable") requirements. See `[std::condition\_variable](condition_variable "cpp/thread/condition variable")` for the description of the semantics of condition variables. The class `std::condition_variable_any` is a [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). It is not [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), or [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). If the lock is `std::unique_lock<std::mutex>`, `[std::condition\_variable](condition_variable "cpp/thread/condition variable")` may provide better performance. ### Member functions | | | | --- | --- | | [(constructor)](condition_variable_any/condition_variable_any "cpp/thread/condition variable any/condition variable any") | constructs the object (public member function) | | [(destructor)](condition_variable_any/~condition_variable_any "cpp/thread/condition variable any/~condition variable any") | destructs the object (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Notification | | [notify\_one](condition_variable_any/notify_one "cpp/thread/condition variable any/notify one") | notifies one waiting thread (public member function) | | [notify\_all](condition_variable_any/notify_all "cpp/thread/condition variable any/notify all") | notifies all waiting threads (public member function) | | Waiting | | [wait](condition_variable_any/wait "cpp/thread/condition variable any/wait") | blocks the current thread until the condition variable is woken up (public member function) | | [wait\_for](condition_variable_any/wait_for "cpp/thread/condition variable any/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) | | [wait\_until](condition_variable_any/wait_until "cpp/thread/condition variable any/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) | ### Notes `std::condition_variable_any` can be used with `[std::shared\_lock](shared_lock "cpp/thread/shared lock")` in order to wait on a `[std::shared\_mutex](shared_mutex "cpp/thread/shared mutex")` in shared ownership mode. A possible use for `std::condition_variable_any` with custom [Lockable](../named_req/lockable "cpp/named req/Lockable") types is to provide convenient interruptible waits: the custom lock operation would both lock the associated mutex as expected, and also perform the necessary setup to notify this condition variable when the interrupting signal is received.[[1]](#cite_note-1) ### See also | | | | --- | --- | | [condition\_variable](condition_variable "cpp/thread/condition variable") (C++11) | provides a condition variable associated with a `[std::unique\_lock](unique_lock "cpp/thread/unique lock")` (class) | ### External links 1. Anthony Williams (2012, 1st ed./ 2019, 2nd ed.), “C++ Concurrency in Action”, 9.2.4 “Interrupting a wait on `std::condition_variable_any`”. cpp std::stop_callback std::stop\_callback =================== | Defined in header `[<stop\_token>](../header/stop_token "cpp/header/stop token")` | | | | --- | --- | --- | | ``` template< class Callback > class stop_callback; ``` | | (since C++20) | The `stop_callback` class template provides an RAII object type that registers a callback function for an associated [`std::stop_token`](stop_token "cpp/thread/stop token") object, such that the callback function will be invoked when the [`std::stop_token`](stop_token "cpp/thread/stop token")'s associated [`std::stop_source`](stop_source "cpp/thread/stop source") is requested to stop. Callback functions registered via `stop_callback`'s constructor are invoked either in the same thread that successfully invokes `request_stop()` for a [`std::stop_source`](stop_source "cpp/thread/stop source") of the `stop_callback`'s associated [`std::stop_token`](stop_token "cpp/thread/stop token"); or if stop has already been requested prior to the constructor's registration, then the callback is invoked in the thread constructing the `stop_callback`. More than one `stop_callback` can be created for the same [`std::stop_token`](stop_token "cpp/thread/stop token"), from the same or different threads concurrently. No guarantee is provided for the order in which they will be executed, but they will be invoked synchronously; except for `stop_callback`(s) constructed after stop has already been requested for the [`std::stop_token`](stop_token "cpp/thread/stop token"), as described previously. If an invocation of a callback exits via an exception then `[std::terminate](../error/terminate "cpp/error/terminate")` is called. `std::stop_callback` is not [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"), nor [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). The template param `Callback` type must be both [`invocable`](../concepts/invocable "cpp/concepts/invocable") and [`destructible`](../concepts/destructible "cpp/concepts/destructible"). Any return value is ignored. ### Member types | Type | Definition | | --- | --- | | `callback_type` | `Callback` | ### Member functions | | | | --- | --- | | [(constructor)](stop_callback/stop_callback "cpp/thread/stop callback/stop callback") | constructs new stop\_callback object (public member function) | | [(destructor)](stop_callback/~stop_callback "cpp/thread/stop callback/~stop callback") | destructs the stop\_callback object (public member function) | | operator= [deleted] | `stop_callback` is not assignable (public member function) | ### [Deduction guides](stop_callback/deduction_guides "cpp/thread/stop callback/deduction guides") ### Example ``` #include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <sstream> #include <thread> using namespace std::chrono_literals; // Use a helper class for atomic std::cout streaming class Writer { std::ostringstream buffer; public: ~Writer() { std::cout << buffer.str(); } Writer& operator<<(auto input) { buffer << input; return *this; } }; int main() { // A worker thread // It will wait until it is requested to stop. std::jthread worker([] (std::stop_token stoken) { Writer() << "Worker thread's id: " << std::this_thread::get_id() << '\n'; std::mutex mutex; std::unique_lock lock(mutex); std::condition_variable_any().wait(lock, stoken, [&stoken] { return stoken.stop_requested(); }); }); // Register a stop callback on the worker thread. std::stop_callback callback(worker.get_stop_token(), [] { Writer() << "Stop callback executed by thread: " << std::this_thread::get_id() << '\n'; }); // stop_callback objects can be destroyed prematurely to prevent execution { std::stop_callback scoped_callback(worker.get_stop_token(), [] { // This will not be executed. Writer() << "Scoped stop callback executed by thread: " << std::this_thread::get_id() << '\n'; }); } // Demonstrate which thread executes the stop_callback and when. // Define a stopper function auto stopper_func = [&worker] { if(worker.request_stop()) Writer() << "Stop request executed by thread: " << std::this_thread::get_id() << '\n'; else Writer() << "Stop request not executed by thread: " << std::this_thread::get_id() << '\n'; }; // Let multiple threads compete for stopping the worker thread std::jthread stopper1(stopper_func); std::jthread stopper2(stopper_func); stopper1.join(); stopper2.join(); // After a stop has already been requested, // a new stop_callback executes immediately. Writer() << "Main thread: " << std::this_thread::get_id() << '\n'; std::stop_callback callback_after_stop(worker.get_stop_token(), [] { Writer() << "Stop callback executed by thread: " << std::this_thread::get_id() << '\n'; }); } ``` Possible output: ``` Worker thread's id: 140460265039616 Stop callback executed by thread: 140460256646912 Stop request executed by thread: 140460256646912 Stop request not executed by thread: 140460248254208 Main thread: 140460265043776 Stop callback executed by thread: 140460265043776 ``` cpp std::shared_lock std::shared\_lock ================= | Defined in header `[<shared\_mutex>](../header/shared_mutex "cpp/header/shared mutex")` | | | | --- | --- | --- | | ``` template< class Mutex > class shared_lock; ``` | | (since C++14) | The class `shared_lock` is a general-purpose shared mutex ownership wrapper allowing deferred locking, timed locking and transfer of lock ownership. Locking a `shared_lock` locks the associated shared mutex in shared mode (to lock it in exclusive mode, `[std::unique\_lock](unique_lock "cpp/thread/unique lock")` can be used). The `shared_lock` class is movable, but not copyable -- it meets the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") but not of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") or [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). `shared_lock` meets the [Lockable](../named_req/lockable "cpp/named req/Lockable") requirements. If `Mutex` meets the [SharedTimedLockable](../named_req/sharedtimedlockable "cpp/named req/SharedTimedLockable") requirements, `shared_lock` also meets [TimedLockable](../named_req/timedlockable "cpp/named req/TimedLockable") requirements. In order to wait in a shared mutex in shared ownership mode, `[std::condition\_variable\_any](condition_variable_any "cpp/thread/condition variable any")` can be used (`[std::condition\_variable](condition_variable "cpp/thread/condition variable")` requires `[std::unique\_lock](unique_lock "cpp/thread/unique lock")` and so can only wait in unique ownership mode). ### Template parameters | | | | | --- | --- | --- | | Mutex | - | the type of the shared mutex to lock. The type must meet the [SharedLockable](../named_req/sharedlockable "cpp/named req/SharedLockable") requirements | ### Member types | Type | Definition | | --- | --- | | `mutex_type` | `Mutex` | ### Member functions | | | | --- | --- | | [(constructor)](shared_lock/shared_lock "cpp/thread/shared lock/shared lock") | constructs a `shared_lock`, optionally locking the supplied mutex (public member function) | | [(destructor)](shared_lock/~shared_lock "cpp/thread/shared lock/~shared lock") | unlocks the associated mutex (public member function) | | [operator=](shared_lock/operator= "cpp/thread/shared lock/operator=") | unlocks the mutex, if owned, and acquires ownership of another (public member function) | | Shared locking | | [lock](shared_lock/lock "cpp/thread/shared lock/lock") | locks the associated mutex (public member function) | | [try\_lock](shared_lock/try_lock "cpp/thread/shared lock/try lock") | tries to lock the associated mutex (public member function) | | [try\_lock\_for](shared_lock/try_lock_for "cpp/thread/shared lock/try lock for") | tries to lock the associated mutex, for the specified duration (public member function) | | [try\_lock\_until](shared_lock/try_lock_until "cpp/thread/shared lock/try lock until") | tries to lock the associated mutex, until a specified time point (public member function) | | [unlock](shared_lock/unlock "cpp/thread/shared lock/unlock") | unlocks the associated mutex (public member function) | | Modifiers | | [swap](shared_lock/swap "cpp/thread/shared lock/swap") | swaps the data members with another shared\_lock (public member function) | | [release](shared_lock/release "cpp/thread/shared lock/release") | disassociates the mutex without unlocking (public member function) | | Observers | | [mutex](shared_lock/mutex "cpp/thread/shared lock/mutex") | returns a pointer to the associated mutex (public member function) | | [owns\_lock](shared_lock/owns_lock "cpp/thread/shared lock/owns lock") | tests whether the lock owns its associated mutex (public member function) | | [operator bool](shared_lock/operator_bool "cpp/thread/shared lock/operator bool") | tests whether the lock owns its associated mutex (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::shared\_lock)](shared_lock/swap2 "cpp/thread/shared lock/swap2") (C++14) | specialization of `[std::swap](../algorithm/swap "cpp/algorithm/swap")` for `shared_lock` (function template) | ### 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 2981](https://cplusplus.github.io/LWG/issue2981) | C++17 | redundant deduction guide from `shared_lock<Mutex>` was provided | removed | cpp std::lock std::lock ========= | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` template< class Lockable1, class Lockable2, class... LockableN > void lock( Lockable1& lock1, Lockable2& lock2, LockableN&... lockn ); ``` | | (since C++11) | Locks the given [Lockable](../named_req/lockable "cpp/named req/Lockable") objects `lock1`, `lock2`, `...`, `lockn` using a deadlock avoidance algorithm to avoid deadlock. The objects are locked by an unspecified series of calls to `lock`, `try_lock`, and `unlock`. If a call to `lock` or `unlock` results in an exception, `unlock` is called for any locked objects before rethrowing. ### Parameters | | | | | --- | --- | --- | | lock1, lock2, ... , lockn | - | the [Lockable](../named_req/lockable "cpp/named req/Lockable") objects to lock | ### Return value (none). ### Notes [Boost provides a version of this function](http://www.boost.org/doc/libs/release/doc/html/thread/synchronization.html#thread.synchronization.lock_functions.lock_range) that takes a sequence of [Lockable](../named_req/lockable "cpp/named req/Lockable") objects defined by a pair of iterators. [`std::scoped_lock`](scoped_lock "cpp/thread/scoped lock") offers a [RAII](../language/raii "cpp/language/raii") wrapper for this function, and is generally preferred to a naked call to `std::lock`. ### Example The following example uses `std::lock` to lock pairs of mutexes without deadlock. ``` #include <mutex> #include <thread> #include <iostream> #include <vector> #include <functional> #include <chrono> #include <string> struct Employee { Employee(std::string id) : id(id) {} std::string id; std::vector<std::string> lunch_partners; std::mutex m; std::string output() const { std::string ret = "Employee " + id + " has lunch partners: "; for( const auto& partner : lunch_partners ) ret += partner + " "; return ret; } }; void send_mail(Employee &, Employee &) { // simulate a time-consuming messaging operation std::this_thread::sleep_for(std::chrono::seconds(1)); } void assign_lunch_partner(Employee &e1, Employee &e2) { static std::mutex io_mutex; { std::lock_guard<std::mutex> lk(io_mutex); std::cout << e1.id << " and " << e2.id << " are waiting for locks" << std::endl; } // use std::lock to acquire two locks without worrying about // other calls to assign_lunch_partner deadlocking us { std::lock(e1.m, e2.m); std::lock_guard<std::mutex> lk1(e1.m, std::adopt_lock); std::lock_guard<std::mutex> lk2(e2.m, std::adopt_lock); // Equivalent code (if unique_locks are needed, e.g. for condition variables) // std::unique_lock<std::mutex> lk1(e1.m, std::defer_lock); // std::unique_lock<std::mutex> lk2(e2.m, std::defer_lock); // std::lock(lk1, lk2); // Superior solution available in C++17 // std::scoped_lock lk(e1.m, e2.m); { std::lock_guard<std::mutex> lk(io_mutex); std::cout << e1.id << " and " << e2.id << " got locks" << std::endl; } e1.lunch_partners.push_back(e2.id); e2.lunch_partners.push_back(e1.id); } send_mail(e1, e2); send_mail(e2, e1); } int main() { Employee alice("alice"), bob("bob"), christina("christina"), dave("dave"); // assign in parallel threads because mailing users about lunch assignments // takes a long time std::vector<std::thread> threads; threads.emplace_back(assign_lunch_partner, std::ref(alice), std::ref(bob)); threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(bob)); threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(alice)); threads.emplace_back(assign_lunch_partner, std::ref(dave), std::ref(bob)); for (auto &thread : threads) thread.join(); std::cout << alice.output() << '\n' << bob.output() << '\n' << christina.output() << '\n' << dave.output() << '\n'; } ``` Possible output: ``` alice and bob are waiting for locks alice and bob got locks christina and bob are waiting for locks christina and bob got locks christina and alice are waiting for locks christina and alice got locks dave and bob are waiting for locks dave and bob got locks Employee alice has lunch partners: bob christina Employee bob has lunch partners: alice christina dave Employee christina has lunch partners: bob alice Employee dave has lunch partners: bob ``` ### See also | | | | --- | --- | | [unique\_lock](unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | | [try\_lock](try_lock "cpp/thread/try lock") (C++11) | attempts to obtain ownership of mutexes via repeated calls to `try_lock` (function template) | | [scoped\_lock](scoped_lock "cpp/thread/scoped lock") (C++17) | deadlock-avoiding RAII wrapper for multiple mutexes (class template) |
programming_docs
cpp std::future_category std::future\_category ===================== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` const std::error_category& future_category() noexcept; ``` | | (since C++11) | Obtains a reference to the static error category object for the errors related to futures and promises. The object is required to override the virtual function `error_category::name()` to return a pointer to the string `"future"`. It is used to identify error codes provided in the exceptions of type `[std::future\_error](future_error "cpp/thread/future error")`. ### Parameters (none). ### Return value A reference to the static object of unspecified runtime type, derived from `[std::error\_category](../error/error_category "cpp/error/error category")`. ### Example ### See also | | | | --- | --- | | [future\_errc](future_errc "cpp/thread/future errc") (C++11) | identifies the future error codes (enum) | | [future\_error](future_error "cpp/thread/future error") (C++11) | reports an error related to futures or promises (class) | | [error\_category](../error/error_category "cpp/error/error category") (C++11) | base class for error categories (class) | cpp std::stop_source std::stop\_source ================= | Defined in header `[<stop\_token>](../header/stop_token "cpp/header/stop token")` | | | | --- | --- | --- | | ``` class stop_source; ``` | | (since C++20) | The `stop_source` class provides the means to issue a stop request, such as for `std::jthread` cancellation. A stop request made for one `stop_source` object is visible to all `stop_source`s and `std::stop_token`s of the same associated stop-state; any `std::stop_callback`(s) registered for associated `std::stop_token`(s) will be invoked, and any `[std::condition\_variable\_any](condition_variable_any "cpp/thread/condition variable any")` objects waiting on associated `std::stop_token`(s) will be awoken. Once a stop is requested, it cannot be withdrawn. Additional stop requests have no effect. ### Member functions | | | | --- | --- | | [(constructor)](stop_source/stop_source "cpp/thread/stop source/stop source") | constructs new stop\_source object (public member function) | | [(destructor)](stop_source/~stop_source "cpp/thread/stop source/~stop source") | destructs the stop\_source object (public member function) | | [operator=](stop_source/operator= "cpp/thread/stop source/operator=") | assigns the stop\_source object (public member function) | | Modifiers | | [request\_stop](stop_source/request_stop "cpp/thread/stop source/request stop") | makes a stop request for the associated stop-state, if any (public member function) | | [swap](stop_source/swap "cpp/thread/stop source/swap") | swaps two stop\_source objects (public member function) | | Observers | | [get\_token](stop_source/get_token "cpp/thread/stop source/get token") | returns a `stop_token` for the associated stop-state (public member function) | | [stop\_requested](stop_source/stop_requested "cpp/thread/stop source/stop requested") | checks whether the associated stop-state has been requested to stop (public member function) | | [stop\_possible](stop_source/stop_possible "cpp/thread/stop source/stop possible") | checks whether associated stop-state can be requested to stop (public member function) | ### Non-member functions | | | | --- | --- | | [operator==](stop_source/operator_cmp "cpp/thread/stop source/operator cmp") | compares two `std::stop_source` objects (function) | | [swap(std::stop\_source)](stop_source/swap2 "cpp/thread/stop source/swap2") (C++20) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | ### Helper constants | | | | --- | --- | | [nostopstate](stop_source/nostopstate "cpp/thread/stop source/nostopstate") (C++20) | a `std::nostopstate_t` instance for use in `stop_source` constructor (constant) | ### Helper classes | | | | --- | --- | | [nostopstate\_t](stop_source/nostopstate_t "cpp/thread/stop source/nostopstate t") (C++20) | placeholder type for use in `stop_source` constructor (class) | ### Notes For the purposes of `[std::jthread](jthread "cpp/thread/jthread")` cancellation the `stop_source` object should be retrieved from the `[std::jthread](jthread "cpp/thread/jthread")` object using [`get_stop_source()`](jthread/get_stop_source "cpp/thread/jthread/get stop source"); or stop should be requested directly from the `[std::jthread](jthread "cpp/thread/jthread")` object using [`request_stop()`](jthread/request_stop "cpp/thread/jthread/request stop"). This will then use the same associated stop-state as that passed into the `[std::jthread](jthread "cpp/thread/jthread")`'s invoked function argument (i.e., the function being executed on its thread). For other uses, however, a `stop_source` can be constructed separately using the default constructor, which creates new stop-state. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_jthread`](../feature_test#Library_features "cpp/feature test") | ### Example cpp std::thread std::thread =========== | Defined in header `[<thread>](../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` class thread; ``` | | (since C++11) | The class `thread` represents [a single thread of execution](https://en.wikipedia.org/wiki/Thread_(computing) "enwiki:Thread (computing)"). Threads allow multiple functions to execute concurrently. Threads begin execution immediately upon construction of the associated thread object (pending any OS scheduling delays), starting at the top-level function provided as a [constructor argument](thread/thread "cpp/thread/thread/thread"). The return value of the top-level function is ignored and if it terminates by throwing an exception, `[std::terminate](../error/terminate "cpp/error/terminate")` is called. The top-level function may communicate its return value or an exception to the caller via `[std::promise](promise "cpp/thread/promise")` or by modifying shared variables (which may require synchronization, see `[std::mutex](mutex "cpp/thread/mutex")` and `[std::atomic](../atomic/atomic "cpp/atomic/atomic")`). `std::thread` objects may also be in the state that does not represent any thread (after default construction, move from, `[detach](thread/detach "cpp/thread/thread/detach")`, or `[join](thread/join "cpp/thread/thread/join")`), and a thread of execution may not be associated with any `thread` objects (after `[detach](thread/detach "cpp/thread/thread/detach")`). No two `std::thread` objects may represent the same thread of execution; `std::thread` is not [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") or [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"), although it is [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). ### Member types | Member type | Definition | | --- | --- | | `native_handle_type`(not always present) | *implementation-defined* | ### Member classes | | | | --- | --- | | [id](thread/id "cpp/thread/thread/id") | represents the *id* of a thread (public member class) | ### Member functions | | | | --- | --- | | [(constructor)](thread/thread "cpp/thread/thread/thread") | constructs new thread object (public member function) | | [(destructor)](thread/~thread "cpp/thread/thread/~thread") | destructs the thread object, underlying thread must be joined or detached (public member function) | | [operator=](thread/operator= "cpp/thread/thread/operator=") | moves the thread object (public member function) | | Observers | | [joinable](thread/joinable "cpp/thread/thread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | | [get\_id](thread/get_id "cpp/thread/thread/get id") | returns the *id* of the thread (public member function) | | [native\_handle](thread/native_handle "cpp/thread/thread/native handle") | returns the underlying implementation-defined thread handle (public member function) | | [hardware\_concurrency](thread/hardware_concurrency "cpp/thread/thread/hardware concurrency") [static] | returns the number of concurrent threads supported by the implementation (public static member function) | | Operations | | [join](thread/join "cpp/thread/thread/join") | waits for the thread to finish its execution (public member function) | | [detach](thread/detach "cpp/thread/thread/detach") | permits the thread to execute independently from the thread handle (public member function) | | [swap](thread/swap "cpp/thread/thread/swap") | swaps two thread objects (public member function) | ### Non-member functions | | | | --- | --- | | [std::swap(std::thread)](thread/swap2 "cpp/thread/thread/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | ### See also | | | | --- | --- | | [jthread](jthread "cpp/thread/jthread") (C++20) | `std::thread` with support for auto-joining and cancellation (class) | cpp std::cv_status std::cv\_status =============== | Defined in header `[<condition\_variable>](../header/condition_variable "cpp/header/condition variable")` | | | | --- | --- | --- | | ``` enum class cv_status { no_timeout, timeout }; ``` | | (since C++11) | The scoped enumeration `std::cv_status` describes whether a timed wait returned because of timeout or not. `std::cv_status` is used by the `wait_for` and `wait_until` member functions of `[std::condition\_variable](condition_variable "cpp/thread/condition variable")` and `[std::condition\_variable\_any](condition_variable_any "cpp/thread/condition variable any")`. ### Member constants | Constant | Explanation | | --- | --- | | `no_timeout` | the condition variable was awakened with `notify_all`, `notify_one`, or spuriously | | `timeout` | the condition variable was awakened by timeout expiration | ### See also | | | | --- | --- | | [wait\_for](condition_variable/wait_for "cpp/thread/condition variable/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function of `std::condition_variable`) | | [wait\_for](condition_variable_any/wait_for "cpp/thread/condition variable any/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function of `std::condition_variable_any`) | | [wait\_until](condition_variable/wait_until "cpp/thread/condition variable/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function of `std::condition_variable`) | | [wait\_until](condition_variable_any/wait_until "cpp/thread/condition variable any/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function of `std::condition_variable_any`) | cpp std::once_flag std::once\_flag =============== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` class once_flag; ``` | | (since C++11) | The class `std::once_flag` is a helper structure for `[std::call\_once](call_once "cpp/thread/call once")`. An object of type `std::once_flag` that is passed to multiple calls to `[std::call\_once](call_once "cpp/thread/call once")` allows those calls to coordinate with each other such that only one of the calls will actually run to completion. `std::once_flag` is neither copyable nor movable. ### Member functions std::once\_flag::once\_flag ---------------------------- | | | | | --- | --- | --- | | ``` constexpr once_flag() noexcept; ``` | | | Constructs an `once_flag` object. The internal state is set to indicate that no function has been called yet. ### Parameters (none). ### See also | | | | --- | --- | | [call\_once](call_once "cpp/thread/call once") (C++11) | invokes a function only once even if called from multiple threads (function template) | | [C documentation](https://en.cppreference.com/w/c/thread/call_once "c/thread/call once") for `once_flag` | cpp std::shared_future std::shared\_future =================== | Defined in header `[<future>](../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` template< class T > class shared_future; ``` | (1) | (since C++11) | | ``` template< class T > class shared_future<T&>; ``` | (2) | (since C++11) | | ``` template<> class shared_future<void>; ``` | (3) | (since C++11) | The class template `std::shared_future` provides a mechanism to access the result of asynchronous operations, similar to `[std::future](future "cpp/thread/future")`, except that multiple threads are allowed to wait for the same shared state. Unlike `[std::future](future "cpp/thread/future")`, which is only moveable (so only one instance can refer to any particular asynchronous result), `std::shared_future` is copyable and multiple shared future objects may refer to the same shared state. Access to the same shared state from multiple threads is safe if each thread does it through its own copy of a `shared_future` object. ### Member functions | | | | --- | --- | | [(constructor)](shared_future/shared_future "cpp/thread/shared future/shared future") | constructs the future object (public member function) | | [(destructor)](shared_future/~shared_future "cpp/thread/shared future/~shared future") | destructs the future object (public member function) | | [operator=](shared_future/operator= "cpp/thread/shared future/operator=") | assigns the contents (public member function) | | Getting the result | | [get](shared_future/get "cpp/thread/shared future/get") | returns the result (public member function) | | State | | [valid](shared_future/valid "cpp/thread/shared future/valid") | checks if the future has a shared state (public member function) | | [wait](shared_future/wait "cpp/thread/shared future/wait") | waits for the result to become available (public member function) | | [wait\_for](shared_future/wait_for "cpp/thread/shared future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function) | | [wait\_until](shared_future/wait_until "cpp/thread/shared future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function) | ### Example A `shared_future` may be used to signal multiple threads simultaneously, similar to `[std::condition\_variable::notify\_all()](condition_variable/notify_all "cpp/thread/condition variable/notify all")`. ``` #include <iostream> #include <future> #include <chrono> int main() { std::promise<void> ready_promise, t1_ready_promise, t2_ready_promise; std::shared_future<void> ready_future(ready_promise.get_future()); std::chrono::time_point<std::chrono::high_resolution_clock> start; auto fun1 = [&, ready_future]() -> std::chrono::duration<double, std::milli> { t1_ready_promise.set_value(); ready_future.wait(); // waits for the signal from main() return std::chrono::high_resolution_clock::now() - start; }; auto fun2 = [&, ready_future]() -> std::chrono::duration<double, std::milli> { t2_ready_promise.set_value(); ready_future.wait(); // waits for the signal from main() return std::chrono::high_resolution_clock::now() - start; }; auto fut1 = t1_ready_promise.get_future(); auto fut2 = t2_ready_promise.get_future(); auto result1 = std::async(std::launch::async, fun1); auto result2 = std::async(std::launch::async, fun2); // wait for the threads to become ready fut1.wait(); fut2.wait(); // the threads are ready, start the clock start = std::chrono::high_resolution_clock::now(); // signal the threads to go ready_promise.set_value(); std::cout << "Thread 1 received the signal " << result1.get().count() << " ms after start\n" << "Thread 2 received the signal " << result2.get().count() << " ms after start\n"; } ``` Possible output: ``` Thread 1 received the signal 0.072 ms after start Thread 2 received the signal 0.041 ms after start ``` ### See also | | | | --- | --- | | [async](async "cpp/thread/async") (C++11) | runs a function asynchronously (potentially in a new thread) and returns a `[std::future](future "cpp/thread/future")` that will hold the result (function template) | | [future](future "cpp/thread/future") (C++11) | waits for a value that is set asynchronously (class template) | cpp std::recursive_mutex std::recursive\_mutex ===================== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` class recursive_mutex; ``` | | (since C++11) | The `recursive_mutex` class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. `recursive_mutex` offers exclusive, recursive ownership semantics: * A calling thread *owns* a `recursive_mutex` for a period of time that starts when it successfully calls either [`lock`](recursive_mutex/lock "cpp/thread/recursive mutex/lock") or [`try_lock`](mutex/try_lock "cpp/thread/mutex/try lock"). During this period, the thread may make additional calls to [`lock`](recursive_mutex/lock "cpp/thread/recursive mutex/lock") or [`try_lock`](recursive_mutex/try_lock "cpp/thread/recursive mutex/try lock"). The period of ownership ends when the thread makes a matching number of calls to [`unlock`](recursive_mutex/unlock "cpp/thread/recursive mutex/unlock"). * When a thread owns a `recursive_mutex`, all other threads will block (for calls to [`lock`](recursive_mutex/lock "cpp/thread/recursive mutex/lock")) or receive a `false` return value (for [`try_lock`](recursive_mutex/try_lock "cpp/thread/recursive mutex/try lock")) if they attempt to claim ownership of the `recursive_mutex`. * The maximum number of times that a `recursive_mutex` may be locked is unspecified, but after that number is reached, calls to [`lock`](recursive_mutex/lock "cpp/thread/recursive mutex/lock") will throw `[std::system\_error](../error/system_error "cpp/error/system error")` and calls to [`try_lock`](mutex/try_lock "cpp/thread/mutex/try lock") will return `false`. The behavior of a program is undefined if a `recursive_mutex` is destroyed while still owned by some thread. The `recursive_mutex` class satisfies all requirements of [Mutex](../named_req/mutex "cpp/named req/Mutex") and [StandardLayoutType](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"). ### Member types | Member type | Definition | | --- | --- | | `native_handle_type`(not always present) | *implementation-defined* | ### Member functions | | | | --- | --- | | [(constructor)](recursive_mutex/recursive_mutex "cpp/thread/recursive mutex/recursive mutex") | constructs the mutex (public member function) | | [(destructor)](recursive_mutex/~recursive_mutex "cpp/thread/recursive mutex/~recursive mutex") | destroys the mutex (public member function) | | operator= [deleted] | not copy-assignable (public member function) | | Locking | | [lock](recursive_mutex/lock "cpp/thread/recursive mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](recursive_mutex/try_lock "cpp/thread/recursive mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](recursive_mutex/unlock "cpp/thread/recursive mutex/unlock") | unlocks the mutex (public member function) | | Native handle | | [native\_handle](recursive_mutex/native_handle "cpp/thread/recursive mutex/native handle") | returns the underlying implementation-defined native handle object (public member function) | ### Example one use case for `recursive_mutex` is protecting shared state in a class whose member functions may call each other. ``` #include <iostream> #include <thread> #include <mutex> class X { std::recursive_mutex m; std::string shared; public: void fun1() { std::lock_guard<std::recursive_mutex> lk(m); shared = "fun1"; std::cout << "in fun1, shared variable is now " << shared << '\n'; } void fun2() { std::lock_guard<std::recursive_mutex> lk(m); shared = "fun2"; std::cout << "in fun2, shared variable is now " << shared << '\n'; fun1(); // recursive lock becomes useful here std::cout << "back in fun2, shared variable is " << shared << '\n'; }; }; int main() { X x; std::thread t1(&X::fun1, &x); std::thread t2(&X::fun2, &x); t1.join(); t2.join(); } ``` Possible output: ``` in fun1, shared variable is now fun1 in fun2, shared variable is now fun2 in fun1, shared variable is now fun1 back in fun2, shared variable is fun1 ``` ### See also | | | | --- | --- | | [mutex](mutex "cpp/thread/mutex") (C++11) | provides basic mutual exclusion facility (class) |
programming_docs
cpp std::call_once std::call\_once =============== | Defined in header `[<mutex>](../header/mutex "cpp/header/mutex")` | | | | --- | --- | --- | | ``` template< class Callable, class... Args > void call_once( std::once_flag& flag, Callable&& f, Args&&... args ); ``` | | (since C++11) | Executes the [Callable](../named_req/callable "cpp/named req/Callable") object `f` exactly once, even if called concurrently, from several threads. In detail: * If, by the time `call_once` is called, `flag` indicates that `f` was already called, `call_once` returns right away (such a call to `call_once` is known as *passive*). * Otherwise, call\_once invokes `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Callable>(f)` with the arguments `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...` (as if by `[std::invoke](../utility/functional/invoke "cpp/utility/functional/invoke")`). Unlike the `[std::thread](thread "cpp/thread/thread")` constructor or `[std::async](async "cpp/thread/async")`, the arguments are not moved or copied because they don't need to be transferred to another thread of execution. (such a call to `call_once` is known as *active*). + If that invocation throws an exception, it is propagated to the caller of `call_once`, and the flag is not flipped so that another call will be attempted (such a call to `call_once` is known as *exceptional*). + If that invocation returns normally (such a call to `call_once` is known as *returning*), the flag is flipped, and all other calls to `call_once` with the same flag are guaranteed to be *passive*. All *active* calls on the same `flag` form a single total order consisting of zero or more *exceptional* calls, followed by one *returning* call. The end of each *active* call synchronizes-with the next *active* call in that order. The return from the *returning* call synchronizes-with the returns from all *passive* calls on the same `flag`: this means that all concurrent calls to `call_once` are guaranteed to observe any side-effects made by the *active* call, with no additional synchronization. ### Parameters | | | | | --- | --- | --- | | flag | - | an object, for which exactly one function gets executed | | f | - | [Callable](../named_req/callable "cpp/named req/Callable") object to invoke | | args... | - | arguments to pass to the function | ### Return value (none). ### Exceptions * `[std::system\_error](../error/system_error "cpp/error/system error")` if any condition prevents calls to `call_once` from executing as specified * any exception thrown by `f` ### Notes If concurrent calls to call\_once pass different functions `f`, it is unspecified which `f` will be called. The selected function runs in the same thread as the `call_once` invocation it was passed to. Initialization of [function-local statics](../language/storage_duration#Static_local_variables "cpp/language/storage duration") is guaranteed to occur only once even when called from multiple threads, and may be more efficient than the equivalent code using `std::call_once`. The POSIX equivalent of this function is [`pthread_once`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_once.html). ### Example ``` #include <iostream> #include <thread> #include <mutex> std::once_flag flag1, flag2; void simple_do_once() { std::call_once(flag1, [](){ std::cout << "Simple example: called once\n"; }); } void may_throw_function(bool do_throw) { if (do_throw) { std::cout << "throw: call_once will retry\n"; // this may appear more than once throw std::exception(); } std::cout << "Didn't throw, call_once will not attempt again\n"; // guaranteed once } void do_once(bool do_throw) { try { std::call_once(flag2, may_throw_function, do_throw); } catch (...) { } } int main() { std::thread st1(simple_do_once); std::thread st2(simple_do_once); std::thread st3(simple_do_once); std::thread st4(simple_do_once); st1.join(); st2.join(); st3.join(); st4.join(); std::thread t1(do_once, true); std::thread t2(do_once, true); std::thread t3(do_once, false); std::thread t4(do_once, true); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Simple example: called once throw: call_once will retry throw: call_once will retry Didn't throw, call_once will not attempt again ``` ### 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 2442](https://cplusplus.github.io/LWG/issue2442) | C++11 | the arguments are copied and/or moved before invocation | no copying/moving is performed | ### See also | | | | --- | --- | | [once\_flag](once_flag "cpp/thread/once flag") (C++11) | helper object to ensure that **`call_once`** invokes the function only once (class) | | [C documentation](https://en.cppreference.com/w/c/thread/call_once "c/thread/call once") for `call_once` | cpp std::this_thread::yield std::this\_thread::yield ======================== | Defined in header `[<thread>](../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` void yield() noexcept; ``` | | (since C++11) | Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run. ### Parameters (none). ### Return value (none). ### Notes The exact behavior of this function depends on the implementation, in particular on the mechanics of the OS scheduler in use and the state of the system. For example, a first-in-first-out realtime scheduler (`SCHED_FIFO` in Linux) would suspend the current thread and put it on the back of the queue of the same-priority threads that are ready to run (and if there are no other threads at the same priority, `yield` has no effect). ### Example ``` #include <iostream> #include <chrono> #include <thread> // "busy sleep" while suggesting that other threads run // for a small amount of time void little_sleep(std::chrono::microseconds us) { auto start = std::chrono::high_resolution_clock::now(); auto end = start + us; do { std::this_thread::yield(); } while (std::chrono::high_resolution_clock::now() < end); } int main() { auto start = std::chrono::high_resolution_clock::now(); little_sleep(std::chrono::microseconds(100)); auto elapsed = std::chrono::high_resolution_clock::now() - start; std::cout << "waited for " << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count() << " microseconds\n"; } ``` Possible output: ``` waited for 128 microseconds ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_yield "c/thread/thrd yield") for `thrd_yield` | cpp std::timed_mutex::unlock std::timed\_mutex::unlock ========================= | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++11) | Unlocks the mutex. The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent lock operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_unlock "c/thread/mtx unlock") for `mtx_unlock` | cpp std::timed_mutex::timed_mutex std::timed\_mutex::timed\_mutex =============================== | | | | | --- | --- | --- | | ``` timed_mutex(); ``` | (1) | (since C++11) | | ``` timed_mutex( const timed_mutex& ) = delete; ``` | (2) | (since C++11) | 1) Constructs the mutex. The mutex is in unlocked state after the call. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if the construction is unsuccessful. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_init "c/thread/mtx init") for `mtx_init` | cpp std::timed_mutex::try_lock_until std::timed\_mutex::try\_lock\_until =================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > bool try_lock_until( const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | | (since C++11) | Tries to lock the mutex. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_time` has already passed, this function behaves like `[try\_lock()](try_lock "cpp/thread/timed mutex/try lock")`. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false` (since C++20). The standard recommends that the clock tied to `timeout_time` be used, in which case adjustments of the clock may be taken into account. Thus, the duration of the block might, but might not, be less or more than `timeout_time - Clock::now()` at the time of the call, depending on the direction of the adjustment and whether it is honored by the implementation. The function also may block for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. As with `[try\_lock()](try_lock "cpp/thread/timed mutex/try lock")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point before `timeout_time`. Prior `[unlock()](unlock "cpp/thread/timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. If `try_lock_until` is called by a thread that already owns the `mutex`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example This example shows a 10 seconds block. ``` #include <thread> #include <iostream> #include <chrono> #include <mutex> std::timed_mutex test_mutex; void f() { auto now=std::chrono::steady_clock::now(); test_mutex.try_lock_until(now + std::chrono::seconds(10)); std::cout << "hello world\n"; } int main() { std::lock_guard<std::timed_mutex> l(test_mutex); std::thread t(f); t.join(); } ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [unlock](unlock "cpp/thread/timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_timedlock "c/thread/mtx timedlock") for `mtx_timedlock` | cpp std::timed_mutex::try_lock std::timed\_mutex::try\_lock ============================ | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++11) | Tries to lock the mutex. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currently locked by any other thread. If `try_lock` is called by a thread that already owns the `mutex`, the behavior is undefined. Prior `[unlock()](unlock "cpp/thread/timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. Note that prior `[lock()](lock "cpp/thread/timed mutex/lock")` does not synchronize with this operation if it returns `false`. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_trylock "c/thread/mtx trylock") for `mtx_trylock` | cpp std::timed_mutex::~timed_mutex std::timed\_mutex::~timed\_mutex ================================ | | | | | --- | --- | --- | | ``` ~timed_mutex(); ``` | | | Destroys the mutex. The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_destroy "c/thread/mtx destroy") for `mtx_destroy` | cpp std::timed_mutex::native_handle std::timed\_mutex::native\_handle ================================= | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++11) (not always present) | Returns the underlying implementation-defined native handle object. ### Parameters (none). ### Return value Implementation-defined native handle object. ### Exceptions Implementation-defined. ### Example cpp std::timed_mutex::lock std::timed\_mutex::lock ======================= | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++11) | Locks the mutex. If another thread has already locked the mutex, a call to `lock` will block execution until the lock is acquired. If `lock` is called by a thread that already owns the `mutex`, the behavior is undefined: for example, the program *may* deadlock. An implementation that can detect the invalid usage is encouraged to throw a `[std::system\_error](../../error/system_error "cpp/error/system error")` with error condition `resource_deadlock_would_occur` instead of deadlocking. Prior `[unlock()](unlock "cpp/thread/timed mutex/unlock")` operations on the same mutex *synchronize-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`, [`std::scoped_lock`](../scoped_lock "cpp/thread/scoped lock"), and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); ++g_num; // note, that the mutex also syncronizes the output std::cout << "id: " << id << ", g_num: " << g_num << '\n'; g_num_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(234)); } } int main() { std::thread t1{slow_increment, 0}; std::thread t2{slow_increment, 1}; t1.join(); t2.join(); } ``` Possible output: ``` id: 0, g_num: 1 id: 1, g_num: 2 id: 1, g_num: 3 id: 0, g_num: 4 id: 0, g_num: 5 id: 1, g_num: 6 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_lock "c/thread/mtx lock") for `mtx_lock` | cpp std::timed_mutex::try_lock_for std::timed\_mutex::try\_lock\_for ================================= | | | | | --- | --- | --- | | ``` template< class Rep, class Period > bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | | (since C++11) | Tries to lock the mutex. Blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_duration` is less or equal `timeout_duration.zero()`, the function behaves like `[try\_lock()](try_lock "cpp/thread/timed mutex/try lock")`. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a [`steady_clock`](../../chrono/steady_clock "cpp/chrono/steady clock") is used to measure the duration. If an implementation uses a [`system_clock`](../../chrono/system_clock "cpp/chrono/system clock") instead, the wait time may also be sensitive to clock adjustments. As with `[try\_lock()](try_lock "cpp/thread/timed mutex/try lock")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point during `timeout_duration`. Prior `[unlock()](unlock "cpp/thread/timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. If `try_lock_for` is called by a thread that already owns the `mutex`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | minimum duration to block for | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example ``` #include <iostream> #include <mutex> #include <chrono> #include <thread> #include <vector> #include <sstream> using namespace std::chrono_literals; std::mutex cout_mutex; // control access to std::cout std::timed_mutex mutex; void job(int id) { std::ostringstream stream; for (int i = 0; i < 3; ++i) { if (mutex.try_lock_for(100ms)) { stream << "success "; std::this_thread::sleep_for(100ms); mutex.unlock(); } else { stream << "failed "; } std::this_thread::sleep_for(100ms); } std::lock_guard<std::mutex> lock{cout_mutex}; std::cout << "[" << id << "] " << stream.str() << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 4; ++i) { threads.emplace_back(job, i); } for (auto& i: threads) { i.join(); } } ``` Possible output: ``` [0] failed failed failed [3] failed failed success [2] failed success failed [1] success failed success ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/timed mutex/unlock") | unlocks the mutex (public member function) |
programming_docs
cpp std::make_error_code(std::future_errc) std::make\_error\_code(std::future\_errc) ========================================= | Defined in header `[<future>](../../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` std::error_code make_error_code( std::future_errc e ); ``` | | (since C++11) | Constructs an `[std::error\_code](../../error/error_code "cpp/error/error code")` object from a value of type `[std::future\_errc](../future_errc "cpp/thread/future errc")` as if by: `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)(static\_cast<int>(e), [std::future\_category](http://en.cppreference.com/w/cpp/thread/future/future_category)())`. This function is called by the constructor of `[std::error\_code](../../error/error_code "cpp/error/error code")` when given an `[std::future\_errc](../future_errc "cpp/thread/future errc")` argument. ### Parameters | | | | | --- | --- | --- | | e | - | error code number | ### Return value A value of type `[std::error\_code](../../error/error_code "cpp/error/error code")` that holds the error code number from `e` associated with the error category `"future"`. ### Example ### See also | | | | --- | --- | | [error\_code](../../error/error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [future\_errc](../future_errc "cpp/thread/future errc") (C++11) | identifies the future error codes (enum) | | [make\_error\_code(std::errc)](../../error/errc/make_error_code "cpp/error/errc/make error code") (C++11) | constructs an `[std::errc](../../error/errc "cpp/error/errc")` error code (function) | | [make\_error\_code(std::io\_errc)](../../io/io_errc/make_error_code "cpp/io/io errc/make error code") (C++11) | constructs an iostream error code (function) | cpp std::make_error_condition(std::future_errc) std::make\_error\_condition(std::future\_errc) ============================================== | Defined in header `[<future>](../../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` std::error_condition make_error_condition( std::future_errc e ); ``` | | (since C++11) | Constructs an `[std::error\_condition](../../error/error_condition "cpp/error/error condition")` object from a value of type `[std::future\_errc](../future_errc "cpp/thread/future errc")` as if by: `[std::error\_condition](http://en.cppreference.com/w/cpp/error/error_condition)(static\_cast<int>(e), [std::future\_category](http://en.cppreference.com/w/cpp/thread/future/future_category)())`. ### Parameters | | | | | --- | --- | --- | | e | - | error code number | ### Return value A value of type `[std::error\_condition](../../error/error_condition "cpp/error/error condition")` that holds the error code number from `e` associated with the error category `"future"`. ### Example ### See also | | | | --- | --- | | [error\_condition](../../error/error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | | [future\_errc](../future_errc "cpp/thread/future errc") (C++11) | identifies the future error codes (enum) | cpp std::shared_future<T>::wait_for std::shared\_future<T>::wait\_for ================================= | | | | | --- | --- | --- | | ``` template< class Rep, class Period > std::future_status wait_for( const std::chrono::duration<Rep,Period>& timeout_duration ) const; ``` | | (since C++11) | Waits for the result to become available. Blocks until specified `timeout_duration` has elapsed or the result becomes available, whichever comes first. The return value identifies the state of the result. If the future is the result of a call to `[std::async](../async "cpp/thread/async")` that used lazy evaluation, this function returns immediately without waiting. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments. The behavior is undefined if [`valid()`](../future/valid "cpp/thread/future/valid") is `false` before the call to this function. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | maximum duration to block for | ### Return value | Constant | Explanation | | --- | --- | | [`future_status::deferred`](../future_status "cpp/thread/future status") | The shared state contains a deferred function using lazy evaluation, so the result will be computed only when explicitly requested | | [`future_status::ready`](../future_status "cpp/thread/future status") | The result is ready | | [`future_status::timeout`](../future_status "cpp/thread/future status") | The timeout has expired | ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Notes The implementations are encouraged to detect the case when `valid == false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of `[std::future\_errc::no\_state](../future_errc "cpp/thread/future errc")`. ### Example ``` #include <iostream> #include <future> #include <thread> #include <chrono> using namespace std::chrono_literals; int main() { std::shared_future<int> future = std::async(std::launch::async, [](){ std::this_thread::sleep_for(3s); return 8; }); std::cout << "waiting...\n"; std::future_status status; do { switch(status = future.wait_for(1s); status) { case std::future_status::deferred: std::cout << "deferred\n"; break; case std::future_status::timeout: std::cout << "timeout\n"; break; case std::future_status::ready: std::cout << "ready!\n"; break; } } while (status != std::future_status::ready); std::cout << "result is " << future.get() << '\n'; } ``` Possible output: ``` waiting... timeout timeout timeout ready! result is 8 ``` ### See also | | | | --- | --- | | [wait](wait "cpp/thread/shared future/wait") | waits for the result to become available (public member function) | | [wait\_until](wait_until "cpp/thread/shared future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function) | cpp std::shared_future<T>::~shared_future std::shared\_future<T>::~shared\_future ======================================= | | | | | --- | --- | --- | | ``` ~shared_future(); ``` | | (since C++11) | If `*this` is the last object referring to the shared state, destroys the shared state. Otherwise does nothing. cpp std::shared_future<T>::valid std::shared\_future<T>::valid ============================= | | | | | --- | --- | --- | | ``` bool valid() const noexcept; ``` | | (since C++11) | Checks if the future refers to a shared state. This is the case only for futures that were not default-constructed or moved from. Unlike `[std::future](../future "cpp/thread/future")`, `std::shared_future`'s shared state is not invalidated when `get()` is called. The behavior is undefined if any member function other than the destructor, the copy-assignment operator, the move-assignment operator, or `valid` is called on a `shared_future` that does not refer to shared state (although implementations are encouraged to throw `[std::future\_error](../future_error "cpp/thread/future error")` indicating `no_state` in this case). It is valid to move or copy from a shared\_future object for which `valid()` is `false`. ### Parameters (none). ### Return value `true` if \*this refers to a shared state, otherwise `false`. ### Example ``` #include <future> #include <iostream> int main() { std::promise<void> p; std::shared_future<void> f = p.get_future(); std::cout << std::boolalpha; std::cout << f.valid() << '\n'; p.set_value(); std::cout << f.valid() << '\n'; f.get(); std::cout << f.valid() << '\n'; } ``` Output: ``` true true true ``` ### See also | | | | --- | --- | | [wait](wait "cpp/thread/shared future/wait") | waits for the result to become available (public member function) | cpp std::shared_future<T>::operator= std::shared\_future<T>::operator= ================================= | | | | | --- | --- | --- | | | (1) | | | ``` shared_future& operator=( const shared_future& other ); ``` | (since C++11) (until C++17) | | ``` shared_future& operator=( const shared_future& other ) noexcept; ``` | (since C++17) | | ``` shared_future& operator=( shared_future&& other ) noexcept; ``` | (2) | (since C++11) | Assigns the contents of another `shared_future`. 1) Releases any shared state and assigns the contents of `other` to `*this`. After the assignment, `this->valid() == other.valid()`. 2) Releases any shared state and move-assigns the contents of `other` to `*this`. After the assignment, `other.valid() == false` and `[this->valid()](valid "cpp/thread/shared future/valid")` will yield the same value as `other.valid()` before the assignment. ### Parameters | | | | | --- | --- | --- | | other | - | a `std::shared_future` that will transfer state to `*this` | ### Return value `*this`. cpp std::shared_future<T>::wait_until std::shared\_future<T>::wait\_until =================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > std::future_status wait_until( const std::chrono::time_point<Clock,Duration>& timeout_time ) const; ``` | | (since C++11) | `wait_until` waits for a result to become available. It blocks until specified `timeout_time` has been reached or the result becomes available, whichever comes first. The return value indicates why `wait_until` returned. If the future is the result of a call to [`async`](../async "cpp/thread/async") that used lazy evaluation, this function returns immediately without waiting. The behavior is undefined if `[valid()](valid "cpp/thread/shared future/valid")` is `false` before the call to this function, or `Clock` does not meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. (since C++20). ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value | Constant | Explanation | | --- | --- | | [`future_status::deferred`](../future_status "cpp/thread/future status") | The shared state contains a deferred function using lazy evaluation, so the result will be computed only when explicitly requested | | [`future_status::ready`](../future_status "cpp/thread/future status") | The result is ready | | [`future_status::timeout`](../future_status "cpp/thread/future status") | The timeout has expired | ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Notes The implementations are encouraged to detect the case when `valid() == false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of [`future_errc::no_state`](../future_errc "cpp/thread/future errc"). The standard recommends that the clock tied to `timeout_time` be used to measure time; that clock is not required to be a monotonic clock. There are no guarantees regarding the behavior of this function if the clock is adjusted discontinuously, but the existing implementations convert `timeout_time` from `Clock` to `[std::chrono::system\_clock](../../chrono/system_clock "cpp/chrono/system clock")` and delegate to POSIX [`pthread_cond_timedwait`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html) so that the wait honors adjustments to the system clock, but not to the user-provided `Clock`. In any case, the function also may wait for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/thread/shared future/wait") | waits for the result to become available (public member function) | | [wait\_for](wait_for "cpp/thread/shared future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function) | cpp std::shared_future<T>::get std::shared\_future<T>::get =========================== | | | | | --- | --- | --- | | ``` const T& get() const; ``` | (1) | (member only of generic `shared_future` template)(since C++11) | | ``` T& get() const; ``` | (2) | (member only of `shared_future<T&>` template specialization)(since C++11) | | ``` void get() const; ``` | (3) | (member only of `shared_future<void>` template specialization)(since C++11) | The `get` member function waits until the `shared_future` has a valid result and (depending on which template is used) retrieves it. It effectively calls `[wait()](wait "cpp/thread/shared future/wait")` in order to wait for the result. The generic template and two template specializations each contain a single version of `get`. The three versions of `get` differ only in the return type. The behavior is undefined if `[valid()](valid "cpp/thread/shared future/valid")` is `false` before the call to this function. ### Parameters (none). ### Return value 1) Const reference to the value stored in the shared state. Accessing the value through this reference is undefined after the shared state has been destroyed. 2) The reference stored as value in the shared state. 3) Nothing. ### Exceptions If an exception was stored in the shared state referenced by the future (e.g. via a call to [`std::promise::set_exception()`](../promise/set_exception "cpp/thread/promise/set exception")) then that exception will be thrown. ### Notes The implementations are encouraged to detect the case when `[valid()](valid "cpp/thread/shared future/valid")` is `false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of `[std::future\_errc::no\_state](../future_errc "cpp/thread/future errc")`. ### Example ### See also | | | | --- | --- | | [valid](valid "cpp/thread/shared future/valid") | checks if the future has a shared state (public member function) | cpp std::shared_future<T>::shared_future std::shared\_future<T>::shared\_future ====================================== | | | | | --- | --- | --- | | ``` shared_future() noexcept; ``` | (1) | (since C++11) | | | (2) | | | ``` shared_future( const shared_future& other ); ``` | (since C++11) (until C++17) | | ``` shared_future( const shared_future& other ) noexcept; ``` | (since C++17) | | ``` shared_future( std::future<T>&& other ) noexcept; ``` | (3) | (since C++11) | | ``` shared_future( shared_future&& other ) noexcept; ``` | (4) | (since C++11) | Constructs a new `shared_future`. 1) Default constructor. Constructs an empty shared future, that doesn't refer to a shared state, that is `valid() == false`. 2) Constructs a shared future that refers to the same shared state, if any, as `other`. 3-4) Transfers the shared state held by `other` to `*this`. After the construction, `other.valid() == false`, and `this->valid()` returns the same value as `other.valid()` would have returned before the construction. ### Parameters | | | | | --- | --- | --- | | other | - | another future object to initialize with | cpp std::shared_future<T>::wait std::shared\_future<T>::wait ============================ | | | | | --- | --- | --- | | ``` void wait() const; ``` | | (since C++11) | Blocks until the result becomes available. `valid() == true` after the call. The behavior is undefined if `[valid](valid "cpp/thread/shared future/valid")() == false` before the call to this function. ### Parameters (none). ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Notes The implementations are encouraged to detect the case when `valid() == false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of `[std::future\_errc::no\_state](../future_errc "cpp/thread/future errc")`. Calling wait on the same `std::shared_future` from multiple threads is not safe; the intended use is for each thread that waits on the same shared state to have a copy of a `std::shared_future`. ### Example ``` #include <chrono> #include <iostream> #include <future> #include <thread> int fib(int n) { if (n < 3) return 1; else return fib(n-1) + fib(n-2); } int main() { std::shared_future<int> f1 = std::async(std::launch::async, [](){ return fib(40); }); std::shared_future<int> f2 = std::async(std::launch::async, [](){ return fib(43); }); std::cout << "waiting... " << std::flush; const auto start = std::chrono::system_clock::now(); f1.wait(); f2.wait(); const auto diff = std::chrono::system_clock::now() - start; std::cout << std::chrono::duration<double>(diff).count() << " seconds\n"; std::cout << "f1: " << f1.get() << '\n'; std::cout << "f2: " << f2.get() << '\n'; } ``` Possible output: ``` waiting... 1.61803 seconds f1: 102334155 f2: 433494437 ``` ### See also | | | | --- | --- | | [wait\_for](wait_for "cpp/thread/shared future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function) | | [wait\_until](wait_until "cpp/thread/shared future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function) | cpp std::packaged_task<R(Args...)>::reset std::packaged\_task<R(Args...)>::reset ====================================== | | | | | --- | --- | --- | | ``` void reset(); ``` | | (since C++11) | Resets the state abandoning the results of previous executions. New shared state is constructed. Equivalent to `*this = packaged_task(std::move(f))`, where `f` is the stored task. ### Parameters (none). ### Return value (none). ### Exceptions * `[std::future\_error](../future_error "cpp/thread/future error")` if `*this` has no shared state. The error condition is set to [`no_state`](../future_errc "cpp/thread/future errc"). * `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if there was not enough memory for a new shared state. * any exception thrown by the [move constructor](packaged_task "cpp/thread/packaged task/packaged task") of the new `packaged_task` ### Example ``` #include <iostream> #include <cmath> #include <thread> #include <future> int main() { std::packaged_task<int(int,int)> task([](int a, int b) { return std::pow(a, b); }); std::future<int> result = task.get_future(); task(2, 9); std::cout << "2^9 = " << result.get() << '\n'; task.reset(); result = task.get_future(); std::thread task_td(std::move(task), 2, 10); task_td.join(); std::cout << "2^10 = " << result.get() << '\n'; } ``` Output: ``` 2^9 = 512 2^10 = 1024 ``` cpp deduction guides for std::packaged_task deduction guides for `std::packaged_task` ========================================= | Defined in header `[<future>](../../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` template< class R, class... Args > packaged_task( R(*)(Args...) ) -> packaged_task<R(Args...)>; ``` | (1) | (since C++17) | | ``` template< class F > packaged_task( F ) -> packaged_task</*see below*/>; ``` | (2) | (since C++17) | | ``` template< class F > packaged_task( F ) -> packaged_task</*see below*/>; ``` | (3) | (since C++23) | | ``` template< class F > packaged_task( F ) -> packaged_task</*see below*/>; ``` | (4) | (since C++23) | 1) This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::packaged\_task](../packaged_task "cpp/thread/packaged task")` to allow deduction from functions. 2) This overload participates in overload resolution only if `&F::operator()` is well-formed when treated as an unevaluated operand and `decltype(&F::operator())` is of the form `R(G::*)(A...)` (optionally cv-qualified, optionally noexcept, optionally lvalue reference qualified). The deduced type is `[std::packaged\_task](http://en.cppreference.com/w/cpp/thread/packaged_task)<R(A...)>`. 3) This overload participates in overload resolution only if `&F::operator()` is well-formed when treated as an unevaluated operand and `F::operator()` is an [explicit object parameter function](../../language/member_functions#Explicit_object_parameter "cpp/language/member functions") whose type is of form `R(G, A...)` or `R(G, A...) noexcept`. The deduced type is `[std::packaged\_task](http://en.cppreference.com/w/cpp/thread/packaged_task)<R(A...)>`. 4) This overload participates in overload resolution only if `&F::operator()` is well-formed when treated as an unevaluated operand and `F::operator()` is a [static member function](../../language/static#Static_member_functions "cpp/language/static") whose type is of form `R(A...)` or `R(A...) noexcept`. The deduced type is `[std::packaged\_task](http://en.cppreference.com/w/cpp/thread/packaged_task)<R(A...)>`. ### Notes These deduction guides do not allow deduction from a function with [ellipsis parameter](../../language/variadic_arguments "cpp/language/variadic arguments"), and the `...` in the types is always treated as a [pack expansion](../../language/parameter_pack#Pack_expansion "cpp/language/parameter pack"). ### Example ``` #include <future> int func(double) { return 0; } int main() { std::packaged_task f{func}; // deduces packaged_task<int(double)> int i = 5; std::packaged_task g = [&](double) { return i; }; // deduces packaged_task<int(double)> } ```
programming_docs
cpp std::packaged_task<R(Args...)>::~packaged_task std::packaged\_task<R(Args...)>::~packaged\_task ================================================ | | | | | --- | --- | --- | | ``` ~packaged_task(); ``` | | | Abandons the shared state and destroys the stored task object. As with `[std::promise::~promise](../promise/~promise "cpp/thread/promise/~promise")`, if the shared state is abandoned before it was made ready, an `[std::future\_error](../future_error "cpp/thread/future error")` exception is stored with the error code `[std::future\_errc::broken\_promise](../future_errc "cpp/thread/future errc")`). ### Parameters (none). ### Example cpp std::packaged_task<R(Args...)>::swap std::packaged\_task<R(Args...)>::swap ===================================== | | | | | --- | --- | --- | | ``` void swap( packaged_task& other ) noexcept; ``` | | (since C++11) | Exchanges the shared states and stored tasks of `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | packaged task whose state to swap with | ### Return value (none). ### See also | | | | --- | --- | | [std::swap(std::packaged\_task)](swap2 "cpp/thread/packaged task/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::packaged_task<R(Args...)>::make_ready_at_thread_exit std::packaged\_task<R(Args...)>::make\_ready\_at\_thread\_exit ============================================================== | | | | | --- | --- | --- | | ``` void make_ready_at_thread_exit( ArgTypes... args ); ``` | | (since C++11) | Calls the stored task with forwarded `args` as the arguments. The return value of the task or any exception thrown by it is stored in the shared state of `*this`. The shared state is only made ready after the current thread exits and all objects of *thread local* storage duration are destroyed. ### Parameters | | | | | --- | --- | --- | | args | - | the parameters to pass on invocation of the stored task | ### Return value (none). ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following error conditions: * The stored task has already been invoked. The error category is set to `promise_already_satisfied`. * `*this` has no shared state. The error category is set to [`no_state`](../future_errc "cpp/thread/future errc"). ### Example ``` #include <future> #include <iostream> #include <chrono> #include <thread> #include <functional> #include <utility> void worker(std::future<void>& output) { std::packaged_task<void(bool&)> my_task{ [](bool& done) { done=true; } }; auto result = my_task.get_future(); bool done = false; my_task.make_ready_at_thread_exit(done); // execute task right away std::cout << "worker: done = " << std::boolalpha << done << std::endl; auto status = result.wait_for(std::chrono::seconds(0)); if (status == std::future_status::timeout) std::cout << "worker: result is not ready yet" << std::endl; output = std::move(result); } int main() { std::future<void> result; std::thread{worker, std::ref(result)}.join(); auto status = result.wait_for(std::chrono::seconds(0)); if (status == std::future_status::ready) std::cout << "main: result is ready" << std::endl; } ``` Output: ``` worker: done = true worker: result is not ready yet main: result is ready ``` ### See also | | | | --- | --- | | [operator()](operator() "cpp/thread/packaged task/operator()") | executes the function (public member function) | cpp std::packaged_task<R(Args...)>::operator() std::packaged\_task<R(Args...)>::operator() =========================================== | | | | | --- | --- | --- | | ``` void operator()( ArgTypes... args ); ``` | | (since C++11) | Calls the stored task with `args` as the arguments. The return value of the task or any exceptions thrown are stored in the shared state. The shared state is made ready and any threads waiting for this are unblocked. ### Parameters | | | | | --- | --- | --- | | args | - | the parameters to pass on invocation of the stored task | ### Return value (none). ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following error conditions: * The stored task has already been invoked. The error category is set to [`promise_already_satisfied`](../future_errc "cpp/thread/future errc"). * `*this` has no shared state. The error category is set to [`no_state`](../future_errc "cpp/thread/future errc"). ### 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 2142](https://cplusplus.github.io/LWG/issue2142) | C++11 | A successful call to `operator()` synchronizes with a call to any member function of a `[std::future](../future "cpp/thread/future")` or `[std::shared\_future](../shared_future "cpp/thread/shared future")` that share their shared state with `*this`. | No additional synchronization guarantees other than what's already provided by shared state. | ### See also | | | | --- | --- | | [make\_ready\_at\_thread\_exit](make_ready_at_thread_exit "cpp/thread/packaged task/make ready at thread exit") | executes the function ensuring that the result is ready only once the current thread exits (public member function) | cpp std::packaged_task<R(Args...)>::packaged_task std::packaged\_task<R(Args...)>::packaged\_task =============================================== | | | | | --- | --- | --- | | ``` packaged_task() noexcept; ``` | (1) | (since C++11) | | ``` template <class F> explicit packaged_task( F&& f ); ``` | (2) | (since C++11) | | ``` template <class F, class Allocator> explicit packaged_task( std::allocator_arg_t, const Allocator& a, F&& f ); ``` | (3) | (since C++11) (until C++17) | | ``` packaged_task( const packaged_task& ) = delete; ``` | (4) | (since C++11) | | ``` packaged_task( packaged_task&& rhs ) noexcept; ``` | (5) | (since C++11) | Constructs a new `std::packaged_task` object. 1) Constructs a `std::packaged_task` object with no task and no shared state. 2,3) Constructs a `std::packaged_task` object with a shared state and a copy of the task, initialized with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f)`. The allocator `a` is used to allocate memory necessary to store the task. (until C++17) * These constructors do not (until C++17)This constructor does not (since C++17) participate in overload resolution if `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<F>::type` is the same type as `[std::packaged\_task](http://en.cppreference.com/w/cpp/thread/packaged_task)<R(ArgTypes...)>`. * The program is ill-formed if the `INVOKE<R>([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<F>(f), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...)` expression (described in [Callable](../../named_req/callable "cpp/named req/Callable")) is ill-formed when treated as an unevaluated operand (i.e. `[std::is\_invocable\_r\_v](http://en.cppreference.com/w/cpp/types/is_invocable)<R, F, Args...>` is not `true`) (since C++17). * The behavior is undefined if the invocation on a copy of `f` behaves different from that on `f`. 4) The copy constructor is deleted, `std::packaged_task` is move-only. 5) Constructs a `std::packaged_task` with the shared state and task formerly owned by `rhs`, leaving `rhs` with no shared state and a moved-from task. ### Parameters | | | | | --- | --- | --- | | f | - | the callable target (function, member function, lambda-expression, functor) to execute | | a | - | the allocator to use when storing the task | | rhs | - | the `std::packaged_task` to move from | ### Exceptions 2) Any exceptions thrown by copy/move constructor of `f` and possibly `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if the allocation fails. 3) Any exceptions thrown by copy/move constructor of `f` and by the allocator's `allocate` function if memory allocation fails. ### Example ``` #include <future> #include <iostream> #include <thread> int fib(int n) { if (n < 3) return 1; else return fib(n-1) + fib(n-2); } int main() { std::packaged_task<int(int)> fib_task(&fib); std::cout << "starting task\n"; auto result = fib_task.get_future(); std::thread t(std::move(fib_task), 42); std::cout << "waiting for task to finish..." << std::endl; std::cout << result.get() << '\n'; std::cout << "task complete\n"; t.join(); } ``` Output: ``` starting task waiting for task to finish... 267914296 task complete ``` ### 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 2067](https://cplusplus.github.io/LWG/issue2067) | C++11 | the deleted copy constructor took reference to non-const | made const | cpp std::packaged_task<R(Args...)>::valid std::packaged\_task<R(Args...)>::valid ====================================== | | | | | --- | --- | --- | | ``` bool valid() const noexcept; ``` | | (since C++11) | Checks whether `*this` has a shared state. ### Parameters (none). ### Return value `true` if `*this` has a shared state, `false` otherwise. cpp std::packaged_task<R(Args...)>::get_future std::packaged\_task<R(Args...)>::get\_future ============================================ | | | | | --- | --- | --- | | ``` std::future<R> get_future(); ``` | | (since C++11) | Returns a `future` which shares the same shared state as `*this`. `get_future` can be called only once for each `packaged_task`. ### Parameters (none). ### Return value A future which shares the same shared state as `*this`. ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following error conditions: * The shared state has already been retrieved via a call to `get_future`. The error category is set to [`future_already_retrieved`](../future_errc "cpp/thread/future errc"). * `*this` has no shared state. The error category is set to [`no_state`](../future_errc "cpp/thread/future errc"). cpp std::swap(std::packaged_task) std::swap(std::packaged\_task) ============================== | | | | | --- | --- | --- | | ``` template< class Function, class... Args > void swap( packaged_task<Function(Args...)> &lhs, packaged_task<Function(Args...)> &rhs ) noexcept; ``` | | (since C++11) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::packaged\_task](../packaged_task "cpp/thread/packaged task")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | packaged tasks whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/thread/packaged task/swap") | swaps two task objects (public member function) | cpp std::packaged_task<R(Args...)>::operator= std::packaged\_task<R(Args...)>::operator= ========================================== | | | | | --- | --- | --- | | ``` packaged_task& operator=( const packaged_task& ) = delete; ``` | (1) | (since C++11) | | ``` packaged_task& operator=( packaged_task&& rhs ) noexcept; ``` | (2) | (since C++11) | 1) Copy assignment operator is deleted, `std::packaged_task` is move-only. 2) Releases the shared state, if any, destroys the previously-held task, and moves the shared state and the task owned by `rhs` into `*this`. `rhs` is left without a shared state and with a moved-from task. ### Parameters | | | | | --- | --- | --- | | rhs | - | the `std::packaged_task` to move from | ### 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 2067](https://cplusplus.github.io/LWG/issue2067) | C++11 | the deleted copy assignment operator took reference to non-const | made const | ### Example cpp std::latch::~latch std::latch::~latch ================== | | | | | --- | --- | --- | | ``` ~latch(); ``` | | (since C++20) | Destroys the `latch`. ### Notes The behavior is undefined if any thread is concurrently calling a member function of the `latch`. cpp std::latch::max std::latch::max =============== | | | | | --- | --- | --- | | ``` static constexpr std::ptrdiff_t max() noexcept; ``` | | (since C++20) | Returns the maximum value of the internal counter supported by the implementation. ### Parameters (none). ### Return value The maximum value of the internal counter supported by the implementation. cpp std::latch::arrive_and_wait std::latch::arrive\_and\_wait ============================= | | | | | --- | --- | --- | | ``` void arrive_and_wait( std::ptrdiff_t n = 1 ); ``` | | (since C++20) | Atomically decrements the internal counter by `n` and (if necessary) blocks the calling thread until the counter reaches zero. Equivalent to `count_down(n); wait();`. If `n` is greater than the value of the internal counter or is negative, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | n | - | the value by which the internal counter is decreased | ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. cpp std::latch::latch std::latch::latch ================= | | | | | --- | --- | --- | | ``` constexpr explicit latch( std::ptrdiff_t expected ); ``` | (1) | (since C++20) | | ``` latch( const latch & ) = delete; ``` | (2) | (since C++20) | 1) Constructs a `latch` and initializes its internal counter. The behavior is undefined if `expected` is negative or greater than `max()`. 2) Copy constructor is deleted. `latch` is neither copyable nor movable. ### Parameters | | | | | --- | --- | --- | | expected | - | the initial value of the internal counter | ### Exceptions Throws nothing. cpp std::latch::try_wait std::latch::try\_wait ===================== | | | | | --- | --- | --- | | ``` bool try_wait() const noexcept; ``` | | (since C++20) | Returns `true` only if the internal counter has reached zero. This function may spuriously return `false` with very low probability even if the internal counter has reached zero. ### Parameters (none). ### Return value With very low probability `false`, otherwise `cnt == 0`, where `cnt` is the value of the internal counter. ### Notes The reason why a spurious result is permitted is to allow implementations to use a memory order more relaxed than `[std::memory\_order\_seq\_cst](../../atomic/memory_order "cpp/atomic/memory order")`. cpp std::latch::count_down std::latch::count\_down ======================= | | | | | --- | --- | --- | | ``` void count_down( std::ptrdiff_t n = 1 ); ``` | | (since C++20) | Atomically decrements the internal counter by `n` without blocking the caller. If `n` is greater than the value of the internal counter or is negative, the behavior is undefined. This operation [strongly happens-before](../../atomic/memory_order#Strongly_happens-before "cpp/atomic/memory order") all calls that are unblocked on this `latch`. ### Parameters | | | | | --- | --- | --- | | n | - | the value by which the internal counter is decreased | ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. cpp std::latch::wait std::latch::wait ================ | | | | | --- | --- | --- | | ``` void wait() const; ``` | | (since C++20) | Blocks the calling thread until the internal counter reaches `0`. If it is zero already, returns immediately. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. cpp std::scoped_lock<MutexTypes...>::scoped_lock std::scoped\_lock<MutexTypes...>::scoped\_lock ============================================== | | | | | --- | --- | --- | | ``` explicit scoped_lock( MutexTypes&... m ); ``` | (1) | (since C++17) | | ``` scoped_lock( std::adopt_lock_t, MutexTypes&... m ); ``` | (2) | (since C++17) | | ``` scoped_lock( const scoped_lock& ) = delete; ``` | (3) | (since C++17) | Acquires ownership of the given mutexes `m`. 1) If `sizeof...(MutexTypes) == 0`, does nothing. Otherwise, if `sizeof...(MutexTypes) == 1`, effectively calls `m.lock()`. Otherwise, effectively calls `[std::lock](http://en.cppreference.com/w/cpp/thread/lock)(m...)`. 2) Acquires ownership of the mutexes `m...` without attempting to lock any of them. The behavior is undefined unless the current thread holds a non-shared lock (i.e., a lock acquired by `lock`, `try_lock`, `try_lock_for`, or `try_lock_until`) on each object in `m...`. 3) Copy constructor is deleted. The behavior is undefined if `m` is destroyed before the `scoped_lock` object is. ### Parameters | | | | | --- | --- | --- | | m | - | mutexes to acquire ownership of | ### Exceptions 1) Throws any exceptions thrown by `m.lock()` 2) 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 | | --- | --- | --- | --- | | [P0739R0](https://wg21.link/p0739r0) | C++17 | `adopt_lock_t` parameter was last, impeding class template argument deduction | moved to first | cpp std::scoped_lock<MutexTypes...>::~scoped_lock std::scoped\_lock<MutexTypes...>::~scoped\_lock =============================================== | | | | | --- | --- | --- | | ``` ~scoped_lock(); ``` | | (since C++17) | Releases the ownership of the owned mutexes. Effectively calls `unlock()` on every mutex from the pack of mutexes passed to the `scoped_lock`'s constructor. cpp std::condition_variable_any::wait_for std::condition\_variable\_any::wait\_for ======================================== | | | | | --- | --- | --- | | ``` template< class Lock, class Rep, class Period > std::cv_status wait_for( Lock& lock, const std::chrono::duration<Rep, Period>& rel_time); ``` | (1) | (since C++11) | | ``` template< class Lock, class Rep, class Period, class Predicate > bool wait_for( Lock& lock, const std::chrono::duration<Rep, Period>& rel_time, Predicate stop_waiting); ``` | (2) | (since C++11) | | ``` template< class Lock, class Rep, class Period, class Predicate > bool wait_for( Lock& lock, std::stop_token stoken, const std::chrono::duration<Rep, Period>& rel_time, Predicate stop_waiting); ``` | (3) | (since C++20) | 1) Atomically releases `lock`, blocks the current executing thread, and adds it to the list of threads waiting on `*this`. The thread will be unblocked when `[notify\_all()](notify_all "cpp/thread/condition variable any/notify all")` or `[notify\_one()](notify_one "cpp/thread/condition variable any/notify one")` is executed, or when the relative timeout `rel_time` expires. It may also be unblocked spuriously. When unblocked, regardless of the reason, `lock` is reacquired and `wait_for()` exits. 2) Equivalent to `return wait_until(lock, [std::chrono::steady\_clock::now](http://en.cppreference.com/w/cpp/chrono/steady_clock/now)() + rel_time, std::move(stop_waiting));`. This overload may be used to ignore spurious awakenings by looping until some predicate is satisfied (`bool(stop_waiting()) == true`). 3) Equivalent to `return wait_until(lock, std::move(stoken), [std::chrono::steady\_clock::now](http://en.cppreference.com/w/cpp/chrono/steady_clock/now)() + rel_time, std::move(stop_waiting));` The standard recommends that a steady clock be used to measure the duration. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. If these functions fail to meet the postcondition (`lock` is locked by the calling thread), `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. For example, this could happen if relocking the mutex throws an exception. ### Parameters | | | | | --- | --- | --- | | lock | - | an object of type `Lock` that meets the [BasicLockable](../../named_req/basiclockable "cpp/named req/BasicLockable") requirements, which must be locked by the current thread | | stoken | - | a `std::stop_token` to register interruption for | | rel\_time | - | an object of type `[std::chrono::duration](../../chrono/duration "cpp/chrono/duration")` representing the maximum time to spend waiting. Note that rel\_time must be small enough not to overflow when added to `[std::chrono::steady\_clock::now()](../../chrono/steady_clock/now "cpp/chrono/steady clock/now")`. | | stop\_waiting | - | predicate which returns ​`false` if the waiting should be continued (`bool(stop_waiting()) == false`). The signature of the predicate function should be equivalent to the following: `bool pred();`​ | ### Return value 1) `[std::cv\_status::timeout](../cv_status "cpp/thread/cv status")` if the relative timeout specified by `rel_time` expired, `[std::cv\_status::no\_timeout](../cv_status "cpp/thread/cv status")` otherwise. 2) `false` if the predicate `stop_waiting` still evaluates to `false` after the `rel_time` timeout expired, otherwise `true`. 3) `stop_waiting()`, regardless of whether the timeout was met or stop was requested. ### Exceptions 1) Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw) 2) Same as (1) but may also propagate exceptions thrown by `stop_waiting` 3) Same as (2) ### Notes Even if notified under lock, overload (1) makes no guarantees about the state of the associated predicate when returning due to timeout. The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. ### Example ``` #include <iostream> #include <atomic> #include <condition_variable> #include <thread> #include <chrono> using namespace std::chrono_literals; std::condition_variable_any cv; std::mutex cv_m; int i; void waits(int idx) { std::unique_lock<std::mutex> lk(cv_m); if(cv.wait_for(lk, idx*100ms, []{return i == 1;})) std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n'; else std::cerr << "Thread " << idx << " timed out. i == " << i << '\n'; } void signals() { std::this_thread::sleep_for(120ms); std::cerr << "Notifying...\n"; cv.notify_all(); std::this_thread::sleep_for(100ms); { std::lock_guard<std::mutex> lk(cv_m); i = 1; } std::cerr << "Notifying again...\n"; cv.notify_all(); } int main() { std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Output: ``` Thread 1 timed out. i == 0 Notifying... Thread 2 timed out. i == 0 Notifying again... Thread 3 finished waiting. i == 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 2093](https://cplusplus.github.io/LWG/issue2093) | C++11 | timeout-related exceptions were missing in the specification | mentioned | | [LWG 2135](https://cplusplus.github.io/LWG/issue2135) | C++11 | `wait_for` threw an exception on unlocking/relocking failure | calls `[std::terminate](../../error/terminate "cpp/error/terminate")` | ### See also | | | | --- | --- | | [wait](wait "cpp/thread/condition variable any/wait") | blocks the current thread until the condition variable is woken up (public member function) | | [wait\_until](wait_until "cpp/thread/condition variable any/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) |
programming_docs
cpp std::condition_variable_any::notify_one std::condition\_variable\_any::notify\_one ========================================== | | | | | --- | --- | --- | | ``` void notify_one() noexcept; ``` | | (since C++11) | If any threads are waiting on `*this`, calling `notify_one` unblocks one of the waiting threads. ### Parameters (none). ### Return value (none). ### Notes The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock. However, some implementations (in particular many implementations of pthreads) recognize this situation and avoid this "hurry up and wait" scenario by transferring the waiting thread from the condition variable's queue directly to the queue of the mutex within the notify call, without waking it up. Notifying while under the lock may nevertheless be necessary when precise scheduling of events is required, e.g. if the waiting thread would exit the program if the condition is satisfied, causing destruction of the notifying thread's condition variable. A spurious wakeup after mutex unlock but before notify would result in notify called on a destroyed object. ### Example ``` #include <iostream> #include <condition_variable> #include <thread> #include <chrono> using namespace std::chrono_literals; std::condition_variable_any cv; std::mutex cv_m; int i = 0; bool done = false; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cout << "Waiting... \n"; cv.wait(lk, []{return i == 1;}); std::cout << "...finished waiting; i == " << i << '\n'; done = true; } void signals() { std::this_thread::sleep_for(200ms); std::cout << "Notifying falsely...\n"; cv.notify_one(); // waiting thread is notified with i == 0. // cv.wait wakes up, checks i, and goes back to waiting std::unique_lock<std::mutex> lk(cv_m); i = 1; while (!done) { std::cout << "Notifying true change...\n"; lk.unlock(); cv.notify_one(); // waiting thread is notified with i == 1, cv.wait returns std::this_thread::sleep_for(300ms); lk.lock(); } } int main() { std::thread t1(waits), t2(signals); t1.join(); t2.join(); } ``` Possible output: ``` Waiting... Notifying falsely... Notifying true change... ...finished waiting; i == 1 ``` ### See also | | | | --- | --- | | [notify\_all](notify_all "cpp/thread/condition variable any/notify all") | notifies all waiting threads (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_signal "c/thread/cnd signal") for `cnd_signal` | cpp std::condition_variable_any::condition_variable_any std::condition\_variable\_any::condition\_variable\_any ======================================================= | | | | | --- | --- | --- | | ``` condition_variable_any(); ``` | (1) | (since C++11) | | ``` condition_variable_any(const condition_variable_any&) = delete; ``` | (2) | (since C++11) | 1) Constructs an object of type `std::condition_variable_any`. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions 1) May throw `[std::system\_error](../../error/system_error "cpp/error/system error")` with `[std::error\_condition](../../error/error_condition "cpp/error/error condition")` equal to `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` if the thread has no privilege to create a condition variable, `[std::errc::resource\_unavailable\_try\_again](../../error/errc "cpp/error/errc")` if a non-memory resource limitation prevents this initialization, or another implementation-defined value. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_init "c/thread/cnd init") for `cnd_init` | cpp std::condition_variable_any::~condition_variable_any std::condition\_variable\_any::~condition\_variable\_any ======================================================== | | | | | --- | --- | --- | | ``` ~condition_variable_any(); ``` | | (since C++11) | Destroys the object of type `[std::condition\_variable\_any](../condition_variable_any "cpp/thread/condition variable any")`. It is only safe to invoke the destructor if all threads have been notified. It is not required that they have exited their respective wait functions: some threads may still be waiting to reacquire the associated lock, or may be waiting to be scheduled to run after reacquiring it. The programmer must ensure that no threads attempt to wait on `*this` once the destructor has been started, especially when the waiting threads are calling the wait functions in a loop or are using the overloads of the wait functions that take a predicate. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_destroy "c/thread/cnd destroy") for `cnd_destroy` | cpp std::condition_variable_any::wait_until std::condition\_variable\_any::wait\_until ========================================== | | | | | --- | --- | --- | | ``` template< class Lock, class Clock, class Duration > std::cv_status wait_until( Lock& lock, const std::chrono::time_point<Clock, Duration>& timeout_time ); ``` | (1) | (since C++11) | | ``` template< class Lock, class Clock, class Duration, class Predicate > bool wait_until( Lock& lock, const std::chrono::time_point<Clock, Duration>& timeout_time, Predicate stop_waiting ); ``` | (2) | (since C++11) | | ``` template< class Lock, class Clock, class Duration, class Predicate > bool wait_until( Lock& lock, std::stop_token stoken, const std::chrono::time_point<Clock, Duration>& timeout_time, Predicate stop_waiting ); ``` | (3) | (since C++20) | `wait_until` causes the current thread to block until the condition variable is notified, a specific time is reached, or a spurious wakeup occurs, optionally looping until some predicate is satisfied (`bool(stop_waiting()) == true`). 1) Atomically releases `lock`, blocks the current executing thread, and adds it to the list of threads waiting on `*this`. The thread will be unblocked when `[notify\_all()](notify_all "cpp/thread/condition variable any/notify all")` or `[notify\_one()](notify_one "cpp/thread/condition variable any/notify one")` is executed, or when the absolute time point `timeout_time` is reached. It may also be unblocked spuriously. When unblocked, regardless of the reason, `lock` is reacquired and `wait_until` exits. 2) Equivalent to ``` while (!stop_waiting()) { if (wait_until(lock, timeout_time) == std::cv_status::timeout) { return stop_waiting(); } } return true; ``` This overload may be used to ignore spurious wakeups. 3) An interruptible wait: registers the `condition_variable_any` for the duration of `wait_until()`, to be notified if a stop request is made on the given `stoken`'s associated stop-state; it is then equivalent to ``` while (!stoken.stop_requested()) { if (stop_waiting()) return true; if (wait_until(lock, timeout_time) == std::cv_status::timeout) return stop_waiting(); } return stop_waiting(); ``` If these functions fail to meet the postcondition (`lock` is locked by the calling thread), `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. For example, this could happen if relocking the mutex throws an exception. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The program is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. (since C++20). ### Parameters | | | | | --- | --- | --- | | lock | - | an object of type `Lock` that meets the requirements of [BasicLockable](../../named_req/basiclockable "cpp/named req/BasicLockable"), which must be locked by the current thread | | stoken | - | a `std::stop_token` to register interruption for | | timeout\_time | - | an object of type `[std::chrono::time\_point](../../chrono/time_point "cpp/chrono/time point")` representing the time when to stop waiting | | stop\_waiting | - | predicate which returns ​`false` if the waiting should be continued (`bool(stop_waiting()) == false`). The signature of the predicate function should be equivalent to the following: `bool pred();`​ | ### Return value 1) `[std::cv\_status::timeout](../cv_status "cpp/thread/cv status")` if the absolute timeout specified by `timeout_time` was reached, `[std::cv\_status::no\_timeout](../cv_status "cpp/thread/cv status")` otherwise. 2) `false` if the predicate `stop_waiting` still evaluates to `false` after the `timeout_time` timeout expired, otherwise `true`. If the timeout had already expired, evaluates and returns the result of `stop_waiting`. 3) `stop_waiting()`, regardless of whether the timeout was met or stop was requested. ### Exceptions 1) Any exception thrown by clock, time point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw) 2) Same as (1) but may also propagate exceptions thrown by `stop_waiting` 3) Same as (2) ### Notes The standard recommends that the clock tied to `timeout_time` be used to measure time; that clock is not required to be a monotonic clock. There are no guarantees regarding the behavior of this function if the clock is adjusted discontinuously, but the existing implementations convert `timeout_time` from `Clock` to `[std::chrono::system\_clock](../../chrono/system_clock "cpp/chrono/system clock")` and delegate to POSIX [`pthread_cond_timedwait`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html) so that the wait honors adjustments to the system clock, but not to the user-provided `Clock`. In any case, the function also may wait for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. Even if the clock in use is `[std::chrono::steady\_clock](../../chrono/steady_clock "cpp/chrono/steady clock")` or another monotonic clock, a system clock adjustment may induce a spurious wakeup. The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. ### Example ``` #include <iostream> #include <atomic> #include <condition_variable> #include <thread> #include <chrono> using namespace std::chrono_literals; std::condition_variable cv; std::mutex cv_m; std::atomic<int> i{0}; void waits(int idx) { std::unique_lock<std::mutex> lk(cv_m); auto now = std::chrono::system_clock::now(); if(cv.wait_until(lk, now + idx*100ms, [](){return i == 1;})) std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n'; else std::cerr << "Thread " << idx << " timed out. i == " << i << '\n'; } void signals() { std::this_thread::sleep_for(120ms); std::cerr << "Notifying...\n"; cv.notify_all(); std::this_thread::sleep_for(100ms); i = 1; std::cerr << "Notifying again...\n"; cv.notify_all(); } int main() { std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Thread 1 timed out. i == 0 Notifying... Thread 2 timed out. i == 0 Notifying again... Thread 3 finished waiting. i == 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 2093](https://cplusplus.github.io/LWG/issue2093) | C++11 | timeout-related exceptions were missing in the specification | mentioned | | [LWG 2135](https://cplusplus.github.io/LWG/issue2135) | C++11 | `wait_until` threw an exception on unlocking/relocking failure | calls `[std::terminate](../../error/terminate "cpp/error/terminate")` | ### See also | | | | --- | --- | | [wait](wait "cpp/thread/condition variable any/wait") | blocks the current thread until the condition variable is woken up (public member function) | | [wait\_for](wait_for "cpp/thread/condition variable any/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_timedwait "c/thread/cnd timedwait") for `cnd_timedwait` | cpp std::condition_variable_any::notify_all std::condition\_variable\_any::notify\_all ========================================== | | | | | --- | --- | --- | | ``` void notify_all() noexcept; ``` | | (since C++11) | Unblocks all threads currently waiting for `*this`. ### Parameters (none). ### Return value (none). ### Notes The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock. ### Example ``` #include <iostream> #include <condition_variable> #include <thread> #include <chrono> std::condition_variable_any cv; std::mutex cv_m; // This mutex is used for three purposes: // 1) to synchronize accesses to i // 2) to synchronize accesses to std::cerr // 3) for the condition variable cv int i = 0; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "Waiting... \n"; cv.wait(lk, []{return i == 1;}); std::cerr << "...finished waiting. i == 1\n"; } void signals() { std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); std::cerr << "Notifying...\n"; } cv.notify_all(); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); i = 1; std::cerr << "Notifying again...\n"; } cv.notify_all(); } int main() { std::thread t1(waits), t2(waits), t3(waits), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Waiting... Waiting... Waiting... Notifying... Notifying again... ...finished waiting. i == 1 ...finished waiting. i == 1 ...finished waiting. i == 1 ``` ### See also | | | | --- | --- | | [notify\_one](notify_one "cpp/thread/condition variable any/notify one") | notifies one waiting thread (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_broadcast "c/thread/cnd broadcast") for `cnd_broadcast` | cpp std::condition_variable_any::wait std::condition\_variable\_any::wait =================================== | | | | | --- | --- | --- | | ``` template< class Lock > void wait( Lock& lock ); ``` | (1) | (since C++11) | | ``` template< class Lock, class Predicate > void wait( Lock& lock, Predicate stop_waiting ); ``` | (2) | (since C++11) | | ``` template< class Lock, class Predicate > bool wait( Lock& lock, std::stop_token stoken, Predicate stop_waiting ); ``` | (3) | (since C++20) | `wait` causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied (`bool(stop_waiting()) == true`). 1) Atomically unlocks `lock`, blocks the current executing thread, and adds it to the list of threads waiting on `*this`. The thread will be unblocked when `[notify\_all()](notify_all "cpp/thread/condition variable any/notify all")` or `[notify\_one()](notify_one "cpp/thread/condition variable any/notify one")` is executed. It may also be unblocked spuriously. When unblocked, regardless of the reason, `lock` is reacquired and `wait` exits. 2) Equivalent to ``` while (!stop_waiting()) { wait(lock); } ``` This overload may be used to ignore spurious awakenings while waiting for a specific condition to become true. Note that `lock` must be acquired before entering this method, and it is reacquired after `wait(lock)` exits, which means that `lock` can be used to guard access to `stop_waiting()`. 3) An interruptible wait: registers the `condition_variable_any` for the duration of `wait()`, to be notified if a stop request is made on the given `stoken`'s associated stop-state; it is then equivalent to ``` while (!stoken.stop_requested()) { if (stop_waiting()) return true; wait(lock); } return stop_waiting(); ``` Note that the returned value indicates whether `stop_waiting` evaluated to `true`, regardless of whether there was a stop requested or not. If these functions fail to meet the postconditions (`lock` is locked by the calling thread), `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. For example, this could happen if relocking the mutex throws an exception. ### Parameters | | | | | --- | --- | --- | | lock | - | an object of type `Lock` that meets the [BasicLockable](../../named_req/basiclockable "cpp/named req/BasicLockable") requirements, which must be locked by the current thread | | stoken | - | a `std::stop_token` to register interruption for | | stop\_waiting | - | predicate which returns ​`false` if the waiting should be continued (`bool(stop_waiting()) == false`). The signature of the predicate function should be equivalent to the following: `bool pred();`​ | ### Return value 1-2) (none) 3) `stop_waiting()` ### Exceptions 1) Does not throw 2) Same as (1) but may also propagate exceptions thrown by `stop_waiting` 3) Same as (2) ### Notes The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. ### Example ``` #include <iostream> #include <condition_variable> #include <thread> #include <chrono> std::condition_variable_any cv; std::mutex cv_m; // This mutex is used for three purposes: // 1) to synchronize accesses to i // 2) to synchronize accesses to std::cerr // 3) for the condition variable cv int i = 0; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "Waiting... \n"; cv.wait(lk, []{return i == 1;}); std::cerr << "...finished waiting. i == 1\n"; } void signals() { std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); std::cerr << "Notifying...\n"; } cv.notify_all(); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); i = 1; std::cerr << "Notifying again...\n"; } cv.notify_all(); } int main() { std::thread t1(waits), t2(waits), t3(waits), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Waiting... Waiting... Waiting... Notifying... Notifying again... ...finished waiting. i == 1 ...finished waiting. i == 1 ...finished waiting. i == 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 2135](https://cplusplus.github.io/LWG/issue2135) | C++11 | `wait` threw an exception on unlocking/relocking failure | calls `[std::terminate](../../error/terminate "cpp/error/terminate")` | ### See also | | | | --- | --- | | [wait\_for](wait_for "cpp/thread/condition variable any/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) | | [wait\_until](wait_until "cpp/thread/condition variable any/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_wait "c/thread/cnd wait") for `cnd_wait` |
programming_docs
cpp std::barrier<CompletionFunction>::~barrier std::barrier<CompletionFunction>::~barrier ========================================== | | | | | --- | --- | --- | | ``` ~barrier(); ``` | | (since C++20) | Destroys the `barrier`. ### Notes The behavior is undefined if any thread is concurrently calling a member function of the `barrier`. cpp std::barrier<CompletionFunction>::arrive_and_drop std::barrier<CompletionFunction>::arrive\_and\_drop =================================================== | | | | | --- | --- | --- | | ``` void arrive_and_drop(); ``` | | (since C++20) | Decrements the initial expected count for all subsequent phases by one, and then decrements the expected count for the current phase by one. This function is executed atomically. The call to this function [strongly happens-before](../../atomic/memory_order#Strongly_happens-before "cpp/atomic/memory order") the start of the phase completion step for the current phase. The behavior is undefined if the expected count for the current phase is zero. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. ### Notes This function can cause the completion step for the current phase to start. If the current expected count is zero before calling this function, the initial expected count for all subsequent phases is also zero, which means the `barrier` cannot be reused. ### Example cpp std::barrier<CompletionFunction>::barrier std::barrier<CompletionFunction>::barrier ========================================= | | | | | --- | --- | --- | | ``` constexpr explicit barrier( std::ptrdiff_t expected, CompletionFunction f = CompletionFunction()); ``` | (1) | (since C++20) | | ``` barrier( const barrier & ) = delete; ``` | (2) | (since C++20) | 1) Sets the both initial expected count for each phase and the current expected count for the first phase to `expected`, initializes the completion function object with `std::move(f)`, and then starts the first phase. The behavior is undefined if `expected` is negative or greater than [`max()`](max "cpp/thread/barrier/max"). 2) Copy constructor is deleted. `barrier` is neither copyable nor movable. ### Parameters | | | | | --- | --- | --- | | expected | - | initial value of the expected count | | f | - | completion function object to be called on phase completion step | ### Exceptions 1) Any exception thrown by `CompletionFunction`'s move constructor. ### Notes `expected` is permitted to be zero. However, calling any non-static member function other than the destructor on such `barrier` results in undefined behavior. In other words, such `barrier` can only be destroyed. cpp std::barrier<CompletionFunction>::max std::barrier<CompletionFunction>::max ===================================== | | | | | --- | --- | --- | | ``` static constexpr std::ptrdiff_t max() noexcept; ``` | | (since C++20) | Returns the maximum value of the expected count supported by the implementation. ### Parameters (none). ### Return value The maximum value of the expected count supported by the implementation. cpp std::barrier<CompletionFunction>::arrive_and_wait std::barrier<CompletionFunction>::arrive\_and\_wait =================================================== | | | | | --- | --- | --- | | ``` void arrive_and_wait(); ``` | | (since C++20) | Atomically decrements the expected count by 1, then blocks at the synchronization point for the current phase until the phase completion step of the current phase is run. Equivalent to `wait(arrive());`. The behavior is undefined if the expected count for the current phase is zero. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. ### Notes If the current expected count is decremented to zero in the call to this function, the phase completion step is run and this function does not block. If the current expected count is zero before calling this function, the initial expected count for all subsequent phases is also zero, which means the `barrier` cannot be reused. ### Example cpp std::barrier<CompletionFunction>::wait std::barrier<CompletionFunction>::wait ====================================== | | | | | --- | --- | --- | | ``` void wait( arrival_token&& arrival ) const; ``` | | (since C++20) | If `arrival` is associated with the phase synchronization point for the current phase of `*this`, blocks at the synchronization point associated with `arrival` until the phase completion step of the synchronization point's phase is run. Otherwise, if `arrival` is associated with the phase synchronization point for the immediately preceding phase of `*this`, returns immediately. Otherwise, i.e. if `arrival` is associated with the phase synchronization point for an earlier phase of `*this` or any phase of a barrier object other than `*this`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | arrival | - | an `arrival_token` obtained by a previous call to [`arrive`](arrive "cpp/thread/barrier/arrive") on the same `barrier` | ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. ### Example ### See also | | | | --- | --- | | [arrive](arrive "cpp/thread/barrier/arrive") | arrives at barrier and decrements the expected count (public member function) | cpp std::barrier<CompletionFunction>::arrive std::barrier<CompletionFunction>::arrive ======================================== | | | | | --- | --- | --- | | ``` [[nodiscard]] arrival_token arrive( std::ptrdiff_t n = 1 ); ``` | | (since C++20) | Constructs an `arrival_token` object associated with the phase synchronization point for the current phase. Then, decrements the expected count by `n`. This function executes atomically. The call to this function [strongly happens-before](../../atomic/memory_order#Strongly_happens-before "cpp/atomic/memory order") the start of the phase completion step for the current phase. The behavior is undefined if `n` is less than or equal to 0 or greater than the expected count for the current barrier phase. ### Parameters | | | | | --- | --- | --- | | n | - | the value by which the expected count is decreased | ### Return value The constructed `arrival_token` object. ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code allowed for mutex types on error. ### Notes This function can cause the completion step for the current phase to start. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/thread/barrier/wait") | blocks at the phase synchronization point until its phase completion step is run (public member function) | cpp std::shared_mutex::shared_mutex std::shared\_mutex::shared\_mutex ================================= | | | | | --- | --- | --- | | ``` shared_mutex(); ``` | (1) | (since C++17) | | ``` shared_mutex( const shared_mutex& ) = delete; ``` | (2) | (since C++17) | 1) Constructs the mutex. The mutex is in unlocked state after the call. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if the construction is unsuccessful. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_init "c/thread/mtx init") for `mtx_init` | cpp std::shared_mutex::unlock std::shared\_mutex::unlock ========================== | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++17) | Unlocks the mutex. The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent lock operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/shared mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_unlock "c/thread/mtx unlock") for `mtx_unlock` | cpp std::shared_mutex::unlock_shared std::shared\_mutex::unlock\_shared ================================== | | | | | --- | --- | --- | | ``` void unlock_shared(); ``` | | (since C++17) | Releases the mutex from shared ownership by the calling thread. The mutex must be locked by the current thread of execution in shared mode, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent `[lock()](lock "cpp/thread/shared mutex/lock")` operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock_shared()` is usually not called directly: `[std::shared\_lock](../shared_lock "cpp/thread/shared lock")` is used to manage shared locking. ### Example ### See also | | | | --- | --- | | [lock\_shared](lock_shared "cpp/thread/shared mutex/lock shared") | locks the mutex for shared ownership, blocks if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/shared mutex/unlock") | unlocks the mutex (public member function) | cpp std::shared_mutex::try_lock_shared std::shared\_mutex::try\_lock\_shared ===================================== | | | | | --- | --- | --- | | ``` bool try_lock_shared(); ``` | | (since C++17) | Tries to lock the mutex in shared mode. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currenly exclusively locked by any other thread. A prior `[unlock()](unlock "cpp/thread/shared mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. The behavior is undefined if the calling thread already owns the mutex in any mode. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/shared mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock\_shared](unlock_shared "cpp/thread/shared mutex/unlock shared") | unlocks the mutex (shared ownership) (public member function) | cpp std::shared_mutex::lock_shared std::shared\_mutex::lock\_shared ================================ | | | | | --- | --- | --- | | ``` void lock_shared(); ``` | | (since C++17) | Acquires shared ownership of the mutex. If another thread is holding the mutex in exclusive ownership, a call to `lock_shared` will block execution until shared ownership can be acquired. If `lock_shared` is called by a thread that already owns the `mutex` in any mode (exclusive or shared), the behavior is undefined. If more than the implementation-defined maximum number of shared owners already locked the mutex in shared mode, `lock_shared` blocks execution until the number of shared owners is reduced. The maximum number of owners is guaranteed to be at least 10000. A prior `[unlock()](unlock "cpp/thread/shared mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock_shared()` is usually not called directly: `[std::shared\_lock](../shared_lock "cpp/thread/shared lock")` is used to manage shared locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock\_shared](try_lock_shared "cpp/thread/shared mutex/try lock shared") | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) | | [unlock\_shared](unlock_shared "cpp/thread/shared mutex/unlock shared") | unlocks the mutex (shared ownership) (public member function) | cpp std::shared_mutex::~shared_mutex std::shared\_mutex::~shared\_mutex ================================== | | | | | --- | --- | --- | | ``` ~shared_mutex(); ``` | | | Destroys the mutex. The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_destroy "c/thread/mtx destroy") for `mtx_destroy` | cpp std::shared_mutex::try_lock std::shared\_mutex::try\_lock ============================= | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++17) | Tries to lock the mutex. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currently locked by any other thread. If `try_lock` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. Prior `[unlock()](unlock "cpp/thread/shared mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. Note that prior `[lock()](lock "cpp/thread/shared mutex/lock")` does not synchronize with this operation if it returns `false`. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/shared mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_trylock "c/thread/mtx trylock") for `mtx_trylock` | cpp std::shared_mutex::native_handle std::shared\_mutex::native\_handle ================================== | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++17) (not always present) | Returns the underlying implementation-defined native handle object. ### Parameters (none). ### Return value Implementation-defined native handle object. ### Exceptions Implementation-defined. ### Example cpp std::shared_mutex::lock std::shared\_mutex::lock ======================== | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++17) | Locks the mutex. If another thread has already locked the mutex, a call to `lock` will block execution until the lock is acquired. If `lock` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. Prior `[unlock()](unlock "cpp/thread/shared mutex/unlock")` operations on the same mutex *synchronize-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`, [`std::scoped_lock`](../scoped_lock "cpp/thread/scoped lock"), and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. Shared mutexes do not support direct transition from shared to unique ownership mode: the shared lock has to be relinquished with `[unlock\_shared()](unlock_shared "cpp/thread/shared mutex/unlock shared")` before exclusive ownership may be obtained with `lock()`. [boost::upgrade\_mutex](http://www.boost.org/doc/libs/release/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.upgrade_mutex) may be used for this purpose. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); ++g_num; // note, that the mutex also syncronizes the output std::cout << "id: " << id << ", g_num: " << g_num << '\n'; g_num_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(234)); } } int main() { std::thread t1{slow_increment, 0}; std::thread t2{slow_increment, 1}; t1.join(); t2.join(); } ``` Possible output: ``` id: 0, g_num: 1 id: 1, g_num: 2 id: 1, g_num: 3 id: 0, g_num: 4 id: 0, g_num: 5 id: 1, g_num: 6 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/shared mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/shared mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_lock "c/thread/mtx lock") for `mtx_lock` | cpp std::condition_variable::wait_for std::condition\_variable::wait\_for =================================== | | | | | --- | --- | --- | | ``` template< class Rep, class Period > std::cv_status wait_for( std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time); ``` | (1) | (since C++11) | | ``` template< class Rep, class Period, class Predicate > bool wait_for( std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time, Predicate stop_waiting); ``` | (2) | (since C++11) | 1) Atomically releases `lock`, blocks the current executing thread, and adds it to the list of threads waiting on `*this`. The thread will be unblocked when `[notify\_all()](notify_all "cpp/thread/condition variable/notify all")` or `[notify\_one()](notify_one "cpp/thread/condition variable/notify one")` is executed, or when the relative timeout `rel_time` expires. It may also be unblocked spuriously. When unblocked, regardless of the reason, `lock` is reacquired and `wait_for()` exits. 2) Equivalent to `return wait_until(lock, [std::chrono::steady\_clock::now](http://en.cppreference.com/w/cpp/chrono/steady_clock/now)() + rel_time, std::move(stop_waiting));`. This overload may be used to ignore spurious awakenings by looping until some predicate is satisfied (`bool(stop_waiting()) == true`). The standard recommends that a steady clock be used to measure the duration. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. Calling this function if `lock.mutex()` is not locked by the current thread is undefined behavior. Calling this function if `lock.mutex()` is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior. If these functions fail to meet the postcondition (`lock.owns_lock()==true` and `lock.mutex()` is locked by the calling thread), `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. For example, this could happen if relocking the mutex throws an exception. ### Parameters | | | | | --- | --- | --- | | lock | - | an object of type `[std::unique\_lock](http://en.cppreference.com/w/cpp/thread/unique_lock)<[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)>`, which must be locked by the current thread | | rel\_time | - | an object of type `[std::chrono::duration](../../chrono/duration "cpp/chrono/duration")` representing the maximum time to spend waiting. Note that rel\_time must be small enough not to overflow when added to `[std::chrono::steady\_clock::now()](../../chrono/steady_clock/now "cpp/chrono/steady clock/now")`. | | stop\_waiting | - | predicate which returns ​`false` if the waiting should be continued (`bool(stop_waiting()) == false`). The signature of the predicate function should be equivalent to the following: `bool pred();`​ | ### Return value 1) `[std::cv\_status::timeout](../cv_status "cpp/thread/cv status")` if the relative timeout specified by `rel_time` expired, `[std::cv\_status::no\_timeout](../cv_status "cpp/thread/cv status")` otherwise. 2) `false` if the predicate `stop_waiting` still evaluates to `false` after the `rel_time` timeout expired, otherwise `true`. ### Exceptions 1) Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw) 2) Same as (1) but may also propagate exceptions thrown by `stop_waiting` ### Notes Even if notified under lock, overload (1) makes no guarantees about the state of the associated predicate when returning due to timeout. The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. ### Example ``` #include <iostream> #include <atomic> #include <condition_variable> #include <thread> #include <chrono> using namespace std::chrono_literals; std::condition_variable cv; std::mutex cv_m; int i; void waits(int idx) { std::unique_lock<std::mutex> lk(cv_m); if(cv.wait_for(lk, idx*100ms, []{return i == 1;})) std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n'; else std::cerr << "Thread " << idx << " timed out. i == " << i << '\n'; } void signals() { std::this_thread::sleep_for(120ms); std::cerr << "Notifying...\n"; cv.notify_all(); std::this_thread::sleep_for(100ms); { std::lock_guard<std::mutex> lk(cv_m); i = 1; } std::cerr << "Notifying again...\n"; cv.notify_all(); } int main() { std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Output: ``` Thread 1 timed out. i == 0 Notifying... Thread 2 timed out. i == 0 Notifying again... Thread 3 finished waiting. i == 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 2093](https://cplusplus.github.io/LWG/issue2093) | C++11 | timeout-related exceptions were missing in the specification | mentioned | | [LWG 2135](https://cplusplus.github.io/LWG/issue2135) | C++11 | `wait_for` threw an exception on unlocking/relocking failure | calls `[std::terminate](../../error/terminate "cpp/error/terminate")` | ### See also | | | | --- | --- | | [wait](wait "cpp/thread/condition variable/wait") | blocks the current thread until the condition variable is woken up (public member function) | | [wait\_until](wait_until "cpp/thread/condition variable/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) |
programming_docs
cpp std::condition_variable::notify_one std::condition\_variable::notify\_one ===================================== | | | | | --- | --- | --- | | ``` void notify_one() noexcept; ``` | | (since C++11) | If any threads are waiting on `*this`, calling `notify_one` unblocks one of the waiting threads. ### Parameters (none). ### Return value (none). ### Notes The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock. However, some implementations (in particular many implementations of pthreads) recognize this situation and avoid this "hurry up and wait" scenario by transferring the waiting thread from the condition variable's queue directly to the queue of the mutex within the notify call, without waking it up. Notifying while under the lock may nevertheless be necessary when precise scheduling of events is required, e.g. if the waiting thread would exit the program if the condition is satisfied, causing destruction of the notifying thread's condition variable. A spurious wakeup after mutex unlock but before notify would result in notify called on a destroyed object. ### Example ``` #include <iostream> #include <condition_variable> #include <thread> #include <chrono> using namespace std::chrono_literals; std::condition_variable cv; std::mutex cv_m; int i = 0; bool done = false; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cout << "Waiting... \n"; cv.wait(lk, []{return i == 1;}); std::cout << "...finished waiting; i == " << i << '\n'; done = true; } void signals() { std::this_thread::sleep_for(200ms); std::cout << "Notifying falsely...\n"; cv.notify_one(); // waiting thread is notified with i == 0. // cv.wait wakes up, checks i, and goes back to waiting std::unique_lock<std::mutex> lk(cv_m); i = 1; while (!done) { std::cout << "Notifying true change...\n"; lk.unlock(); cv.notify_one(); // waiting thread is notified with i == 1, cv.wait returns std::this_thread::sleep_for(300ms); lk.lock(); } } int main() { std::thread t1(waits), t2(signals); t1.join(); t2.join(); } ``` Possible output: ``` Waiting... Notifying falsely... Notifying true change... ...finished waiting; i == 1 ``` ### See also | | | | --- | --- | | [notify\_all](notify_all "cpp/thread/condition variable/notify all") | notifies all waiting threads (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_signal "c/thread/cnd signal") for `cnd_signal` | cpp std::condition_variable::condition_variable std::condition\_variable::condition\_variable ============================================= | | | | | --- | --- | --- | | ``` condition_variable(); ``` | (1) | (since C++11) | | ``` condition_variable(const condition_variable&) = delete; ``` | (2) | (since C++11) | 1) Constructs an object of type `std::condition_variable`. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions 1) May throw `[std::system\_error](../../error/system_error "cpp/error/system error")` with `[std::error\_condition](../../error/error_condition "cpp/error/error condition")` equal to `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` if the thread has no privilege to create a condition variable, `[std::errc::resource\_unavailable\_try\_again](../../error/errc "cpp/error/errc")` if a non-memory resource limitation prevents this initialization, or another implementation-defined value. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_init "c/thread/cnd init") for `cnd_init` | cpp std::condition_variable::~condition_variable std::condition\_variable::~condition\_variable ============================================== | | | | | --- | --- | --- | | ``` ~condition_variable(); ``` | | (since C++11) | Destroys the object of type `[std::condition\_variable](../condition_variable "cpp/thread/condition variable")`. It is only safe to invoke the destructor if all threads have been notified. It is not required that they have exited their respective wait functions: some threads may still be waiting to reacquire the associated lock, or may be waiting to be scheduled to run after reacquiring it. The programmer must ensure that no threads attempt to wait on `*this` once the destructor has been started, especially when the waiting threads are calling the wait functions in a loop or are using the overloads of the wait functions that take a predicate. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_destroy "c/thread/cnd destroy") for `cnd_destroy` | cpp std::condition_variable::native_handle std::condition\_variable::native\_handle ======================================== | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++11) | Accesses the native handle of `*this`. The meaning and the type of the result of this function is implementation-defined. On a POSIX system, this may be a value of type `pthread_cond_t*`. On a Windows system, this may be a `PCONDITION_VARIABLE`. ### Parameters (none). ### Return value The native handle of this condition variable. ### See also | | | | --- | --- | | [native\_handle](../thread/native_handle "cpp/thread/thread/native handle") | returns the underlying implementation-defined thread handle (public member function of `std::thread`) | | [native\_handle](../jthread/native_handle "cpp/thread/jthread/native handle") | returns the underlying implementation-defined thread handle (public member function of `std::jthread`) | cpp std::condition_variable::wait_until std::condition\_variable::wait\_until ===================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > std::cv_status wait_until( std::unique_lock<std::mutex>& lock, const std::chrono::time_point<Clock, Duration>& timeout_time ); ``` | (1) | (since C++11) | | ``` template< class Clock, class Duration, class Predicate > bool wait_until( std::unique_lock<std::mutex>& lock, const std::chrono::time_point<Clock, Duration>& timeout_time, Predicate stop_waiting ); ``` | (2) | (since C++11) | `wait_until` causes the current thread to block until the condition variable is notified, a specific time is reached, or a spurious wakeup occurs, optionally looping until some predicate is satisfied (`bool(stop_waiting()) == true`). 1) Atomically releases `lock`, blocks the current executing thread, and adds it to the list of threads waiting on `*this`. The thread will be unblocked when `[notify\_all()](notify_all "cpp/thread/condition variable/notify all")` or `[notify\_one()](notify_one "cpp/thread/condition variable/notify one")` is executed, or when the absolute time point `timeout_time` is reached. It may also be unblocked spuriously. When unblocked, regardless of the reason, `lock` is reacquired and `wait_until` exits. 2) Equivalent to ``` while (!stop_waiting()) { if (wait_until(lock, timeout_time) == std::cv_status::timeout) { return stop_waiting(); } } return true; ``` This overload may be used to ignore spurious wakeups. Calling this function if `lock.mutex()` is not locked by the current thread is undefined behavior. Calling this function if `lock.mutex()` is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior. If these functions fail to meet the postcondition (`lock.owns_lock()==true` and `lock.mutex()` is locked by the calling thread), `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. For example, this could happen if relocking the mutex throws an exception. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The program is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. (since C++20). ### Parameters | | | | | --- | --- | --- | | lock | - | an object of type std::unique\_lock<std::mutex>, which must be locked by the current thread | | timeout\_time | - | an object of type `[std::chrono::time\_point](../../chrono/time_point "cpp/chrono/time point")` representing the time when to stop waiting | | stop\_waiting | - | predicate which returns ​`false` if the waiting should be continued (`bool(stop_waiting()) == false`). The signature of the predicate function should be equivalent to the following: `bool pred();`​ | ### Return value 1) `[std::cv\_status::timeout](../cv_status "cpp/thread/cv status")` if the absolute timeout specified by `timeout_time` was reached, `[std::cv\_status::no\_timeout](../cv_status "cpp/thread/cv status")` otherwise. 2) `false` if the predicate `stop_waiting` still evaluates to `false` after the `timeout_time` timeout expired, otherwise `true`. If the timeout had already expired, evaluates and returns the result of `stop_waiting`. ### Exceptions 1) Any exception thrown by clock, time point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw) 2) Same as (1) but may also propagate exceptions thrown by `stop_waiting` ### Notes The standard recommends that the clock tied to `timeout_time` be used to measure time; that clock is not required to be a monotonic clock. There are no guarantees regarding the behavior of this function if the clock is adjusted discontinuously, but the existing implementations convert `timeout_time` from `Clock` to `[std::chrono::system\_clock](../../chrono/system_clock "cpp/chrono/system clock")` and delegate to POSIX [`pthread_cond_timedwait`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html) so that the wait honors adjustments to the system clock, but not to the user-provided `Clock`. In any case, the function also may wait for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. Even if the clock in use is `[std::chrono::steady\_clock](../../chrono/steady_clock "cpp/chrono/steady clock")` or another monotonic clock, a system clock adjustment may induce a spurious wakeup. The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. ### Example ``` #include <iostream> #include <atomic> #include <condition_variable> #include <thread> #include <chrono> using namespace std::chrono_literals; std::condition_variable cv; std::mutex cv_m; std::atomic<int> i{0}; void waits(int idx) { std::unique_lock<std::mutex> lk(cv_m); auto now = std::chrono::system_clock::now(); if(cv.wait_until(lk, now + idx*100ms, [](){return i == 1;})) std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n'; else std::cerr << "Thread " << idx << " timed out. i == " << i << '\n'; } void signals() { std::this_thread::sleep_for(120ms); std::cerr << "Notifying...\n"; cv.notify_all(); std::this_thread::sleep_for(100ms); i = 1; std::cerr << "Notifying again...\n"; cv.notify_all(); } int main() { std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Thread 1 timed out. i == 0 Notifying... Thread 2 timed out. i == 0 Notifying again... Thread 3 finished waiting. i == 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 2093](https://cplusplus.github.io/LWG/issue2093) | C++11 | timeout-related exceptions were missing in the specification | mentioned | | [LWG 2135](https://cplusplus.github.io/LWG/issue2135) | C++11 | `wait_until` threw an exception on unlocking/relocking failure | calls `[std::terminate](../../error/terminate "cpp/error/terminate")` | ### See also | | | | --- | --- | | [wait](wait "cpp/thread/condition variable/wait") | blocks the current thread until the condition variable is woken up (public member function) | | [wait\_for](wait_for "cpp/thread/condition variable/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_timedwait "c/thread/cnd timedwait") for `cnd_timedwait` | cpp std::condition_variable::notify_all std::condition\_variable::notify\_all ===================================== | | | | | --- | --- | --- | | ``` void notify_all() noexcept; ``` | | (since C++11) | Unblocks all threads currently waiting for `*this`. ### Parameters (none). ### Return value (none). ### Notes The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock. ### Example ``` #include <iostream> #include <condition_variable> #include <thread> #include <chrono> std::condition_variable cv; std::mutex cv_m; // This mutex is used for three purposes: // 1) to synchronize accesses to i // 2) to synchronize accesses to std::cerr // 3) for the condition variable cv int i = 0; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "Waiting... \n"; cv.wait(lk, []{return i == 1;}); std::cerr << "...finished waiting. i == 1\n"; } void signals() { std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); std::cerr << "Notifying...\n"; } cv.notify_all(); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); i = 1; std::cerr << "Notifying again...\n"; } cv.notify_all(); } int main() { std::thread t1(waits), t2(waits), t3(waits), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Waiting... Waiting... Waiting... Notifying... Notifying again... ...finished waiting. i == 1 ...finished waiting. i == 1 ...finished waiting. i == 1 ``` ### See also | | | | --- | --- | | [notify\_one](notify_one "cpp/thread/condition variable/notify one") | notifies one waiting thread (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_broadcast "c/thread/cnd broadcast") for `cnd_broadcast` | cpp std::condition_variable::wait std::condition\_variable::wait ============================== | | | | | --- | --- | --- | | ``` void wait( std::unique_lock<std::mutex>& lock ); ``` | (1) | (since C++11) | | ``` template< class Predicate > void wait( std::unique_lock<std::mutex>& lock, Predicate stop_waiting ); ``` | (2) | (since C++11) | `wait` causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied (`bool(stop_waiting()) == true`). 1) Atomically unlocks `lock`, blocks the current executing thread, and adds it to the list of threads waiting on `*this`. The thread will be unblocked when `[notify\_all()](notify_all "cpp/thread/condition variable/notify all")` or `[notify\_one()](notify_one "cpp/thread/condition variable/notify one")` is executed. It may also be unblocked spuriously. When unblocked, regardless of the reason, `lock` is reacquired and `wait` exits. 2) Equivalent to ``` while (!stop_waiting()) { wait(lock); } ``` This overload may be used to ignore spurious awakenings while waiting for a specific condition to become true. Note that `lock` must be acquired before entering this method, and it is reacquired after `wait(lock)` exits, which means that `lock` can be used to guard access to `stop_waiting()`. If these functions fail to meet the postconditions (`lock.owns_lock()==true` and `lock.mutex()` is locked by the calling thread), `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. For example, this could happen if relocking the mutex throws an exception. ### Parameters | | | | | --- | --- | --- | | lock | - | an object of type `[std::unique\_lock](http://en.cppreference.com/w/cpp/thread/unique_lock)<[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)>`, which must be locked by the current thread | | stop\_waiting | - | predicate which returns ​`false` if the waiting should be continued (`bool(stop_waiting()) == false`). The signature of the predicate function should be equivalent to the following: `bool pred();`​ | ### Return value (none). ### Exceptions 1) Does not throw 2) Same as (1) but may also propagate exceptions thrown by `stop_waiting` ### Notes Calling this function if [`lock.mutex()`](../unique_lock/mutex "cpp/thread/unique lock/mutex") is not locked by the current thread is undefined behavior. Calling this function if [`lock.mutex()`](../unique_lock/mutex "cpp/thread/unique lock/mutex") is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior. The effects of `notify_one()`/`notify_all()` and each of the three atomic parts of `wait()`/`wait_for()`/`wait_until()` (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as [modification order](../../atomic/memory_order#Modification_order "cpp/atomic/memory order") of an atomic variable: the order is specific to this individual condition variable. This makes it impossible for `notify_one()` to, for example, be delayed and unblock a thread that started waiting just after the call to `notify_one()` was made. ### Example ``` #include <iostream> #include <condition_variable> #include <thread> #include <chrono> std::condition_variable cv; std::mutex cv_m; // This mutex is used for three purposes: // 1) to synchronize accesses to i // 2) to synchronize accesses to std::cerr // 3) for the condition variable cv int i = 0; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "Waiting... \n"; cv.wait(lk, []{return i == 1;}); std::cerr << "...finished waiting. i == 1\n"; } void signals() { std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); std::cerr << "Notifying...\n"; } cv.notify_all(); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); i = 1; std::cerr << "Notifying again...\n"; } cv.notify_all(); } int main() { std::thread t1(waits), t2(waits), t3(waits), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); } ``` Possible output: ``` Waiting... Waiting... Waiting... Notifying... Notifying again... ...finished waiting. i == 1 ...finished waiting. i == 1 ...finished waiting. i == 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 2135](https://cplusplus.github.io/LWG/issue2135) | C++11 | `wait` threw an exception on unlocking/relocking failure | calls `[std::terminate](../../error/terminate "cpp/error/terminate")` | ### See also | | | | --- | --- | | [wait\_for](wait_for "cpp/thread/condition variable/wait for") | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) | | [wait\_until](wait_until "cpp/thread/condition variable/wait until") | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/cnd_wait "c/thread/cnd wait") for `cnd_wait` |
programming_docs
cpp std::stop_callback<Callback>::~stop_callback std::stop\_callback<Callback>::~stop\_callback ============================================== | | | | | --- | --- | --- | | ``` ~stop_callback(); ``` | | (since C++20) | Destroys the `stop_callback` object. If `*this` has a `stop_token` with associated stop-state, deregisters the callback from it. If the callback function is being invoked concurrently on another thread, the destructor does not complete until the callback function invocation is complete. If the callback function is being invoked on the same thread the destructor is being invoked on, then the destructor returns without waiting for callback invocation to complete (see Notes). ### Notes The `stop_callback` destructor is designed to prevent race conditions and deadlocks. If another thread is currently invoking the callback, then the destructor cannot return until that completes, or else the function object could potentially be destroyed while it is being executed. The callback function is not required to be neither copyable nor movable - it lives in the `stop_callback` object itself even after registration. On the other hand, if the current thread invoking the destructor is the same thread that is invoking the callback, then the destructor cannot wait or else a deadlock would occur. It is possible and valid for the same thread to be destroying the `stop_callback` while it is invoking its callback function, because the callback function might itself destroy the `stop_callback`, directly or indirectly. cpp deduction guides for std::stop_callback deduction guides for `std::stop_callback` ========================================= | Defined in header `[<stop\_token>](../../header/stop_token "cpp/header/stop token")` | | | | --- | --- | --- | | ``` template<class Callback> stop_callback(std::stop_token, Callback) -> stop_callback<Callback>; ``` | | (since C++20) | One [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::stop\_callback](../stop_callback "cpp/thread/stop callback")` to permit deduction from argument of invocable types. ### Example cpp std::stop_callback<Callback>::stop_callback std::stop\_callback<Callback>::stop\_callback ============================================= | | | | | --- | --- | --- | | ``` template<class C> explicit stop_callback( const std::stop_token& st, C&& cb ) noexcept(/*see below*/); ``` | (1) | (since C++20) | | ``` template<class C> explicit stop_callback( std::stop_token&& st, C&& cb ) noexcept(/*see below*/); ``` | (2) | (since C++20) | | ``` stop_callback( const stop_callback& ) = delete; ``` | (3) | (since C++20) | | ``` stop_callback( stop_callback&& ) = delete; ``` | (4) | (since C++20) | Constructs a new `stop_callback` object, saving and registering the `cb` callback function into the given [`std::stop_token`](../stop_token "cpp/thread/stop token")'s associated stop-state, for later invocation if stop is requested on the associated [`std::stop_source`](../stop_source "cpp/thread/stop source"). 1) Constructs a `stop_callback` for the given `st` [`std::stop_token`](../stop_token "cpp/thread/stop token") (copied), with the given invocable callback function `cb`. 2) Constructs a `stop_callback` for the given `st` [`std::stop_token`](../stop_token "cpp/thread/stop token") (moved), with the given invocable callback function `cb`. 3-4) `stop_callback` is neither [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") nor [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible"). Both constructors participate overload resolution only if `Callback` and `C` satisfy [`constructible_from`](../../concepts/constructible_from "cpp/concepts/constructible from") of `[std::constructible\_from](http://en.cppreference.com/w/cpp/concepts/constructible_from)<Callback, C>`. If `Callback` and `C` satisfy the concept but fail to satisfy its semantic requirement, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | st | - | a [`std::stop_token`](../stop_token "cpp/thread/stop token") object to register this `stop_callback` object with | | cb | - | the type to invoke if stop is requested | ### Exceptions 1-2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<Callback, C>)` Any exception thrown by constructor-initializing the given callback into the `stop_callback` object. ### Notes If `st.stop_requested() == true` for the passed-in [`std::stop_token`](../stop_token "cpp/thread/stop token"), then the callback function is invoked in the current thread before the constructor returns. cpp std::recursive_mutex::unlock std::recursive\_mutex::unlock ============================= | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++11) | Unlocks the mutex if its level of ownership is `1` (there was exactly one more call to `[lock()](lock "cpp/thread/recursive mutex/lock")` than there were calls to `unlock()` made by this thread), reduces the level of ownership by 1 otherwise. The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent lock operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/recursive mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/recursive mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_unlock "c/thread/mtx unlock") for `mtx_unlock` | cpp std::recursive_mutex::~recursive_mutex std::recursive\_mutex::~recursive\_mutex ======================================== | | | | | --- | --- | --- | | ``` ~recursive_mutex(); ``` | | | Destroys the mutex. The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_destroy "c/thread/mtx destroy") for `mtx_destroy` | cpp std::recursive_mutex::try_lock std::recursive\_mutex::try\_lock ================================ | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++11) | Tries to lock the mutex. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currently locked by any other thread. A thread may call `try_lock` on a recursive mutex repeatedly. Successful calls to `try_lock` increment the ownership count: the mutex will only be released after the thread makes a matching number of calls to `[unlock](unlock "cpp/thread/recursive mutex/unlock")`. The maximum number of levels of ownership is unspecified. A call to `try_lock` will return `false` if this number is exceeded. Prior `[unlock()](unlock "cpp/thread/recursive mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. Note that prior `[lock()](lock "cpp/thread/recursive mutex/lock")` does not synchronize with this operation if it returns `false`. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ``` #include <iostream> #include <mutex> int main() { std::recursive_mutex test; if (test.try_lock()) { std::cout << "lock acquired\n"; test.unlock(); } else { std::cout << "lock not acquired\n"; } test.lock(); // non-recursive mutex would return false from try_lock now if (test.try_lock()) { std::cout << "lock acquired\n"; test.unlock(); } else { std::cout << "lock not acquired\n"; } test.unlock(); } ``` Output: ``` lock acquired lock acquired ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/recursive mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/recursive mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_trylock "c/thread/mtx trylock") for `mtx_trylock` | cpp std::recursive_mutex::native_handle std::recursive\_mutex::native\_handle ===================================== | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++11) (not always present) | Returns the underlying implementation-defined native handle object. ### Parameters (none). ### Return value Implementation-defined native handle object. ### Exceptions Implementation-defined. ### Example cpp std::recursive_mutex::lock std::recursive\_mutex::lock =========================== | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++11) | Locks the mutex. If another thread has already locked the mutex, a call to `lock` will block execution until the lock is acquired. A thread may call `lock` on a recursive mutex repeatedly. Ownership will only be released after the thread makes a matching number of calls to `unlock`. The maximum number of levels of ownership is unspecified. An exception of type `[std::system\_error](../../error/system_error "cpp/error/system error")` will be thrown if this number is exceeded. Prior `[unlock()](unlock "cpp/thread/recursive mutex/unlock")` operations on the same mutex *synchronize-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`, [`std::scoped_lock`](../scoped_lock "cpp/thread/scoped lock"), and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); ++g_num; // note, that the mutex also syncronizes the output std::cout << "id: " << id << ", g_num: " << g_num << '\n'; g_num_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(234)); } } int main() { std::thread t1{slow_increment, 0}; std::thread t2{slow_increment, 1}; t1.join(); t2.join(); } ``` Possible output: ``` id: 0, g_num: 1 id: 1, g_num: 2 id: 1, g_num: 3 id: 0, g_num: 4 id: 0, g_num: 5 id: 1, g_num: 6 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/recursive mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/recursive mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_lock "c/thread/mtx lock") for `mtx_lock` | cpp std::recursive_mutex::recursive_mutex std::recursive\_mutex::recursive\_mutex ======================================= | | | | | --- | --- | --- | | ``` recursive_mutex(); ``` | (1) | (since C++11) | | ``` recursive_mutex( const recursive_mutex& ) = delete; ``` | (2) | (since C++11) | 1) Constructs the mutex. The mutex is in unlocked state after the call. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if the construction is unsuccessful. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_init "c/thread/mtx init") for `mtx_init` | cpp std::unique_lock<Mutex>::mutex std::unique\_lock<Mutex>::mutex =============================== | | | | | --- | --- | --- | | ``` mutex_type* mutex() const noexcept; ``` | | (since C++11) | Returns a pointer to the associated mutex, or a null pointer if there is no associated mutex. ### Parameters (none). ### Return value Pointer to the associated mutex or a null pointer if there is no associated mutex. ### Example cpp std::unique_lock<Mutex>::unlock std::unique\_lock<Mutex>::unlock ================================ | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++11) | Unlocks (i.e., releases ownership of) the associated mutex and releases ownership. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is not locked. ### Parameters (none). ### Return value (none). ### Exceptions * Any exceptions thrown by `mutex()->unlock()` * If there is no associated mutex or the mutex is not locked, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/unique lock/lock") | locks (i.e., takes ownership of) the associated mutex (public member function) | | [release](release "cpp/thread/unique lock/release") | disassociates the associated mutex without unlocking (i.e., releasing ownership of) it (public member function) | cpp std::unique_lock<Mutex>::swap std::unique\_lock<Mutex>::swap ============================== | | | | | --- | --- | --- | | ``` void swap( unique_lock& other ) noexcept; ``` | | (since C++11) | Exchanges the internal states of the lock objects. ### Parameters | | | | | --- | --- | --- | | other | - | the lock to swap the state with | ### Return value (none). ### Example ### See also | | | | --- | --- | | [std::swap(std::unique\_lock)](swap2 "cpp/thread/unique lock/swap2") (C++11) | specialization of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for `unique_lock` (function template) | cpp std::unique_lock<Mutex>::unique_lock std::unique\_lock<Mutex>::unique\_lock ====================================== | | | | | --- | --- | --- | | ``` unique_lock() noexcept; ``` | (1) | (since C++11) | | ``` unique_lock( unique_lock&& other ) noexcept; ``` | (2) | (since C++11) | | ``` explicit unique_lock( mutex_type& m ); ``` | (3) | (since C++11) | | ``` unique_lock( mutex_type& m, std::defer_lock_t t ) noexcept; ``` | (4) | (since C++11) | | ``` unique_lock( mutex_type& m, std::try_to_lock_t t ); ``` | (5) | (since C++11) | | ``` unique_lock( mutex_type& m, std::adopt_lock_t t ); ``` | (6) | (since C++11) | | ``` template< class Rep, class Period > unique_lock( mutex_type& m, const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | (7) | (since C++11) | | ``` template< class Clock, class Duration > unique_lock( mutex_type& m, const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | (8) | (since C++11) | Constructs a `unique_lock`, optionally locking the supplied mutex. 1) Constructs a `unique_lock` with no associated mutex. 2) Move constructor. Initializes the `unique_lock` with the contents of `other`. Leaves `other` with no associated mutex. 3-8) Constructs a `unique_lock` with `m` as the associated mutex. Additionally: 3) Locks the associated mutex by calling `m.lock()`. 4) Does not lock the associated mutex. 5) Tries to lock the associated mutex without blocking by calling `m.try_lock()`. The behavior is undefined if `Mutex` does not satisfy [Lockable](../../named_req/lockable "cpp/named req/Lockable"). 6) Assumes the calling thread already holds an non-shared lock (i.e., a lock acquired by `lock`, `try_lock`, `try_lock_for`, or `try_lock_until`) on `m`. The behavior is undefined if not so. 7) Tries to lock the associated mutex by calling `m.try_lock_for(timeout_duration)`. Blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. May block for longer than `timeout_duration`. The behavior is undefined if `Mutex` does not satisfy [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable"). 8) Tries to lock the associated mutex by calling `m.try_lock_until(timeout_time)`. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. May block for longer than until `timeout_time` has been reached. The behavior is undefined if `Mutex` does not satisfy [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable"). ### Parameters | | | | | --- | --- | --- | | other | - | another `unique_lock` to initialize the state with | | m | - | mutex to associate with the lock and optionally acquire ownership of | | t | - | tag parameter used to select constructors with different locking strategies | | timeout\_duration | - | maximum duration to block for | | timeout\_time | - | maximum time point to block until | ### Example ``` #include <iostream> #include <thread> #include <vector> #include <mutex> std::mutex m_a, m_b, m_c; int a, b, c = 1; void update() { { // Note: std::lock_guard or atomic<int> can be used instead std::unique_lock<std::mutex> lk(m_a); a++; } { // Note: see std::lock and std::scoped_lock for details and alternatives std::unique_lock<std::mutex> lk_b(m_b, std::defer_lock); std::unique_lock<std::mutex> lk_c(m_c, std::defer_lock); std::lock(lk_b, lk_c); b = std::exchange(c, b+c); } } int main() { std::vector<std::thread> threads; for (unsigned i = 0; i < 12; ++i) threads.emplace_back(update); for (auto& i: threads) i.join(); std::cout << a << "'th and " << a+1 << "'th Fibonacci numbers: " << b << " and " << c << '\n'; } ``` Output: ``` 12'th and 13'th Fibonacci numbers: 144 and 233 ``` cpp std::unique_lock<Mutex>::operator bool std::unique\_lock<Mutex>::operator bool ======================================= | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | (since C++11) | Checks whether `*this` owns a locked mutex or not. Effectively calls `[owns\_lock()](owns_lock "cpp/thread/unique lock/owns lock")`. ### Parameters (none). ### Return value `true` if `*this` has an associated mutex and has acquired ownership of it, `false` otherwise. ### See also | | | | --- | --- | | [owns\_lock](owns_lock "cpp/thread/unique lock/owns lock") | tests whether the lock owns (i.e., has locked) its associated mutex (public member function) |
programming_docs
cpp std::unique_lock<Mutex>::release std::unique\_lock<Mutex>::release ================================= | | | | | --- | --- | --- | | ``` mutex_type* release() noexcept; ``` | | (since C++11) | Breaks the association of the associated mutex, if any, and `*this`. No locks are unlocked. If `*this` held ownership of the associated mutex prior to the call, the caller is now responsible to unlock the mutex. ### Parameters (none). ### Return value Pointer to the associated mutex or a null pointer if there was no associated mutex. ### Example ### See also | | | | --- | --- | | [unlock](unlock "cpp/thread/unique lock/unlock") | unlocks (i.e., releases ownership of) the associated mutex (public member function) | cpp std::unique_lock<Mutex>::~unique_lock std::unique\_lock<Mutex>::~unique\_lock ======================================= | | | | | --- | --- | --- | | ``` ~unique_lock(); ``` | | (since C++11) | Destroys the lock. If `*this` has an associated mutex and has acquired ownership of it, the mutex is unlocked. cpp std::unique_lock<Mutex>::try_lock_until std::unique\_lock<Mutex>::try\_lock\_until ========================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > bool try_lock_until( const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | | (since C++11) | Tries to lock (i.e., takes ownership of) the associated mutex. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. May block for longer than `timeout_time` until has been reached. Effectively calls `mutex()->try_lock_until(timeout_time)`. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is already locked by the same thread. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The program is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. (since C++20). ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value `true` if the ownership of the mutex has been acquired successfully, `false` otherwise. ### Exceptions * Any exceptions thrown by `mutex()->try_lock_until(timeout_time)` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the mutex is already locked, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/unique lock/lock") | locks (i.e., takes ownership of) the associated mutex (public member function) | | [try\_lock](try_lock "cpp/thread/unique lock/try lock") | tries to lock (i.e., takes ownership of) the associated mutex without blocking (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/unique lock/try lock for") | attempts to lock (i.e., takes ownership of) the associated [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable for the specified time duration (public member function) | | [unlock](unlock "cpp/thread/unique lock/unlock") | unlocks (i.e., releases ownership of) the associated mutex (public member function) | cpp std::unique_lock<Mutex>::owns_lock std::unique\_lock<Mutex>::owns\_lock ==================================== | | | | | --- | --- | --- | | ``` bool owns_lock() const noexcept; ``` | | (since C++11) | Checks whether `*this` owns a locked mutex or not. ### Parameters (none). ### Return value `true` if `*this` has an associated mutex and has acquired ownership of it, `false` otherwise. ### See also | | | | --- | --- | | [operator bool](operator_bool "cpp/thread/unique lock/operator bool") | tests whether the lock owns (i.e., has locked) its associated mutex (public member function) | cpp std::unique_lock<Mutex>::try_lock std::unique\_lock<Mutex>::try\_lock =================================== | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++11) | Tries to lock (i.e., takes ownership of) the associated mutex without blocking. Effectively calls `mutex()->try_lock()`. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is already locked by this `std::unique_lock`. ### Parameters (none). ### Return value `true` if the ownership of the mutex has been acquired successfully, `false` otherwise. ### Exceptions * Any exceptions thrown by `mutex()->try_lock()` ([Mutex](../../named_req/mutex "cpp/named req/Mutex") types do not throw in `try_lock`, but a custom [Lockable](../../named_req/lockable "cpp/named req/Lockable") might) * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the mutex is already locked by this `std::unique_lock`, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example The following examples try to acquire a mutex that was locked and unlocked. ``` #include <mutex> #include <thread> #include <iostream> #include <vector> #include <chrono> int main() { std::mutex counter_mutex; std::vector<std::thread> threads; auto worker_task = [&](int id, int wait_seconds, int acquire_seconds) { // wait for a few seconds before acquiring lock. std::this_thread::sleep_for(std::chrono::seconds(wait_seconds)); std::unique_lock<std::mutex> lock(counter_mutex, std::defer_lock); if (lock.try_lock()) { std::cout << id << ", lock acquired.\n"; } else { std::cout << id << ", failed acquiring lock.\n"; return; } // keep the lock for a while. std::this_thread::sleep_for(std::chrono::seconds(acquire_seconds)); std::cout << id << ", releasing lock.\n"; lock.unlock(); }; threads.emplace_back(worker_task, 0, 0, 2); threads.emplace_back(worker_task, 1, 1, 0); threads.emplace_back(worker_task, 2, 3, 0); for (auto &thread : threads) thread.join(); } ``` Output: ``` 0, lock acquired. 1, failed acquiring lock. 0, releasing lock. 2, lock acquired. 2, releasing lock. ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/unique lock/lock") | locks (i.e., takes ownership of) the associated mutex (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/unique lock/try lock for") | attempts to lock (i.e., takes ownership of) the associated [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable for the specified time duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/unique lock/try lock until") | tries to lock (i.e., takes ownership of) the associated [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/unique lock/unlock") | unlocks (i.e., releases ownership of) the associated mutex (public member function) | cpp std::swap(std::unique_lock) std::swap(std::unique\_lock) ============================ | | | | | --- | --- | --- | | ``` template< class Mutex > void swap( unique_lock<Mutex>& lhs, unique_lock<Mutex>& rhs ) noexcept; ``` | | (since C++11) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | lock wrappers whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/thread/unique lock/swap") | swaps state with another `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` (public member function) | cpp std::unique_lock<Mutex>::operator= std::unique\_lock<Mutex>::operator= =================================== | | | | | --- | --- | --- | | ``` unique_lock& operator=( unique_lock&& other ); ``` | | (since C++11) | Move assignment operator. Replaces the contents with those of `other` using move semantics. If prior to the call `*this` has an associated mutex and has acquired ownership of it, the mutex is unlocked. ### Parameters | | | | | --- | --- | --- | | other | - | another `unique_lock` to replace the state with | ### Return value `*this`. ### Exceptions Throws nothing. cpp std::unique_lock<Mutex>::lock std::unique\_lock<Mutex>::lock ============================== | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++11) | Locks (i.e., takes ownership of) the associated mutex. Effectively calls `mutex()->lock()`. ### Parameters (none). ### Return value (none). ### Exceptions * Any exceptions thrown by `mutex()->lock()` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the mutex is already locked by this `unique_lock` (in other words, [owns\_lock](owns_lock "cpp/thread/unique lock/owns lock") is true), `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example The following example uses `lock` to re-acquire a mutex that was unlocked. ``` #include <mutex> #include <thread> #include <iostream> #include <vector> #include <chrono> int main() { int counter = 0; std::mutex counter_mutex; std::vector<std::thread> threads; auto worker_task = [&](int id) { std::unique_lock<std::mutex> lock(counter_mutex); ++counter; std::cout << id << ", initial counter: " << counter << '\n'; lock.unlock(); // don't hold the lock while we simulate an expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); lock.lock(); ++counter; std::cout << id << ", final counter: " << counter << '\n'; }; for (int i = 0; i < 10; ++i) threads.emplace_back(worker_task, i); for (auto &thread : threads) thread.join(); } ``` Possible output: ``` 0, initial counter: 1 1, initial counter: 2 2, initial counter: 3 3, initial counter: 4 4, initial counter: 5 5, initial counter: 6 6, initial counter: 7 7, initial counter: 8 8, initial counter: 9 9, initial counter: 10 6, final counter: 11 3, final counter: 12 4, final counter: 13 2, final counter: 14 5, final counter: 15 0, final counter: 16 1, final counter: 17 7, final counter: 18 9, final counter: 19 8, final counter: 20 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/unique lock/try lock") | tries to lock (i.e., takes ownership of) the associated mutex without blocking (public member function) | | [unlock](unlock "cpp/thread/unique lock/unlock") | unlocks (i.e., releases ownership of) the associated mutex (public member function) | cpp std::unique_lock<Mutex>::try_lock_for std::unique\_lock<Mutex>::try\_lock\_for ======================================== | | | | | --- | --- | --- | | ``` template< class Rep, class Period > bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | | (since C++11) | Tries to lock (i.e., takes ownership of) the associated mutex. Blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. Effectively calls `mutex()->try_lock_for(timeout_duration)`. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is already locked by this std::unique\_lock. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | maximum duration to block for | ### Return value `true` if the ownership of the mutex has been acquired successfully, `false` otherwise. ### Exceptions * Any exceptions thrown by `mutex()->try_lock_for(timeout_duration)` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the mutex is already locked, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/unique lock/lock") | locks (i.e., takes ownership of) the associated mutex (public member function) | | [try\_lock](try_lock "cpp/thread/unique lock/try lock") | tries to lock (i.e., takes ownership of) the associated mutex without blocking (public member function) | | [try\_lock\_for](../shared_lock/try_lock_for "cpp/thread/shared lock/try lock for") | tries to lock the associated mutex, for the specified duration (public member function of `std::shared_lock<Mutex>`) | | [try\_lock\_until](try_lock_until "cpp/thread/unique lock/try lock until") | tries to lock (i.e., takes ownership of) the associated [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/unique lock/unlock") | unlocks (i.e., releases ownership of) the associated mutex (public member function) | cpp std::recursive_timed_mutex::~recursive_timed_mutex std::recursive\_timed\_mutex::~recursive\_timed\_mutex ====================================================== | | | | | --- | --- | --- | | ``` ~recursive_timed_mutex(); ``` | | | Destroys the mutex. The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_destroy "c/thread/mtx destroy") for `mtx_destroy` | cpp std::recursive_timed_mutex::unlock std::recursive\_timed\_mutex::unlock ==================================== | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++11) | Unlocks the mutex if its level of ownership is `1` (there was exactly one more call to `[lock()](lock "cpp/thread/recursive timed mutex/lock")` than there were calls to `unlock()` made by this thread), reduces the level of ownership by 1 otherwise. The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent lock operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/recursive timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/recursive timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/recursive timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/recursive timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_unlock "c/thread/mtx unlock") for `mtx_unlock` | cpp std::recursive_timed_mutex::recursive_timed_mutex std::recursive\_timed\_mutex::recursive\_timed\_mutex ===================================================== | | | | | --- | --- | --- | | ``` recursive_timed_mutex(); ``` | (1) | (since C++11) | | ``` recursive_timed_mutex( const recursive_timed_mutex& ) = delete; ``` | (2) | (since C++11) | 1) Constructs the mutex. The mutex is in unlocked state after the call. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if the construction is unsuccessful. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_init "c/thread/mtx init") for `mtx_init` | cpp std::recursive_timed_mutex::try_lock_until std::recursive\_timed\_mutex::try\_lock\_until ============================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > bool try_lock_until( const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | | (since C++11) | Tries to lock the mutex. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_time` has already passed, this function behaves like `[try\_lock()](try_lock "cpp/thread/recursive timed mutex/try lock")`. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false` (since C++20). The standard recommends that the clock tied to `timeout_time` be used, in which case adjustments of the clock may be taken into account. Thus, the duration of the block might, but might not, be less or more than `timeout_time - Clock::now()` at the time of the call, depending on the direction of the adjustment and whether it is honored by the implementation. The function also may block for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. As with `[try\_lock()](try_lock "cpp/thread/recursive timed mutex/try lock")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point before `timeout_time`. Prior `[unlock()](unlock "cpp/thread/recursive timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. A thread may call `try_lock_until` on a recursive mutex repeatedly. Successful calls to `try_lock_until` increment the ownership count: the mutex will only be released after the thread makes a matching number of calls to `[unlock](unlock "cpp/thread/recursive timed mutex/unlock")`. The maximum number of levels of ownership is unspecified. A call to `try_lock_until` will return `false` if this number is exceeded. ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example This example shows a 10 seconds block. ``` #include <thread> #include <iostream> #include <chrono> #include <mutex> std::recursive_timed_mutex test_mutex; void f() { auto now=std::chrono::steady_clock::now(); test_mutex.try_lock_until(now + std::chrono::seconds(10)); std::cout << "hello world\n"; } int main() { std::lock_guard<std::recursive_timed_mutex> l(test_mutex); std::thread t(f); t.join(); } ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/recursive timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/recursive timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/recursive timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [unlock](unlock "cpp/thread/recursive timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_timedlock "c/thread/mtx timedlock") for `mtx_timedlock` |
programming_docs
cpp std::recursive_timed_mutex::try_lock std::recursive\_timed\_mutex::try\_lock ======================================= | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++11) | Tries to lock the mutex. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currently locked by any other thread. A thread may call `try_lock` on a recursive mutex repeatedly. Successful calls to `try_lock` increment the ownership count: the mutex will only be released after the thread makes a matching number of calls to `[unlock](unlock "cpp/thread/recursive timed mutex/unlock")`. The maximum number of levels of ownership is unspecified. A call to `try_lock` will return `false` if this number is exceeded. Prior `[unlock()](unlock "cpp/thread/recursive timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. Note that prior `[lock()](lock "cpp/thread/recursive timed mutex/lock")` does not synchronize with this operation if it returns `false`. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/recursive timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/recursive timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/recursive timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/recursive timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_trylock "c/thread/mtx trylock") for `mtx_trylock` | cpp std::recursive_timed_mutex::native_handle std::recursive\_timed\_mutex::native\_handle ============================================ | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++11) (not always present) | Returns the underlying implementation-defined native handle object. ### Parameters (none). ### Return value Implementation-defined native handle object. ### Exceptions Implementation-defined. ### Example cpp std::recursive_timed_mutex::lock std::recursive\_timed\_mutex::lock ================================== | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++11) | Locks the mutex. If another thread has already locked the mutex, a call to `lock` will block execution until the lock is acquired. A thread may call `lock` on a recursive mutex repeatedly. Ownership will only be released after the thread makes a matching number of calls to `unlock`. The maximum number of levels of ownership is unspecified. An exception of type `[std::system\_error](../../error/system_error "cpp/error/system error")` will be thrown if this number is exceeded. Prior `[unlock()](unlock "cpp/thread/recursive timed mutex/unlock")` operations on the same mutex *synchronize-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`, [`std::scoped_lock`](../scoped_lock "cpp/thread/scoped lock"), and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); ++g_num; // note, that the mutex also syncronizes the output std::cout << "id: " << id << ", g_num: " << g_num << '\n'; g_num_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(234)); } } int main() { std::thread t1{slow_increment, 0}; std::thread t2{slow_increment, 1}; t1.join(); t2.join(); } ``` Possible output: ``` id: 0, g_num: 1 id: 1, g_num: 2 id: 1, g_num: 3 id: 0, g_num: 4 id: 0, g_num: 5 id: 1, g_num: 6 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/recursive timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/recursive timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/recursive timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/recursive timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_lock "c/thread/mtx lock") for `mtx_lock` | cpp std::recursive_timed_mutex::try_lock_for std::recursive\_timed\_mutex::try\_lock\_for ============================================ | | | | | --- | --- | --- | | ``` template< class Rep, class Period > bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | | (since C++11) | Tries to lock the mutex. Blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_duration` is less or equal `timeout_duration.zero()`, the function behaves like `[try\_lock()](try_lock "cpp/thread/recursive timed mutex/try lock")`. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a [`steady_clock`](../../chrono/steady_clock "cpp/chrono/steady clock") is used to measure the duration. If an implementation uses a [`system_clock`](../../chrono/system_clock "cpp/chrono/system clock") instead, the wait time may also be sensitive to clock adjustments. As with `[try\_lock()](try_lock "cpp/thread/recursive timed mutex/try lock")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point during `timeout_duration`. Prior `[unlock()](unlock "cpp/thread/recursive timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. A thread may call `try_lock_for` on a recursive mutex repeatedly. Successful calls to `try_lock_for` increment the ownership count: the mutex will only be released after the thread makes a matching number of calls to `[unlock](unlock "cpp/thread/recursive timed mutex/unlock")`. The maximum number of levels of ownership is unspecified. A call to `try_lock_for` will return `false` if this number is exceeded. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | minimum duration to block for | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example ``` #include <iostream> #include <mutex> #include <chrono> #include <thread> #include <vector> #include <sstream> using namespace std::chrono_literals; std::mutex cout_mutex; // control access to std::cout std::timed_mutex mutex; void job(int id) { std::ostringstream stream; for (int i = 0; i < 3; ++i) { if (mutex.try_lock_for(100ms)) { stream << "success "; std::this_thread::sleep_for(100ms); mutex.unlock(); } else { stream << "failed "; } std::this_thread::sleep_for(100ms); } std::lock_guard<std::mutex> lock{cout_mutex}; std::cout << "[" << id << "] " << stream.str() << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 4; ++i) { threads.emplace_back(job, i); } for (auto& i: threads) { i.join(); } } ``` Possible output: ``` [0] failed failed failed [3] failed failed success [2] failed success failed [1] success failed success ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/recursive timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/recursive timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/recursive timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/recursive timed mutex/unlock") | unlocks the mutex (public member function) | cpp std::promise<R>::~promise std::promise<R>::~promise ========================= | | | | | --- | --- | --- | | ``` ~promise(); ``` | | (since C++11) | Abandons the shared state: * if the shared state is ready, [releases](../promise "cpp/thread/promise") it. * if the shared state is not ready, stores an exception object of type `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition `[std::future\_errc::broken\_promise](../future_errc "cpp/thread/future errc")`, makes the shared state ready and releases it. cpp std::promise<R>::set_exception std::promise<R>::set\_exception =============================== | | | | | --- | --- | --- | | ``` void set_exception( std::exception_ptr p ); ``` | | (since C++11) | Atomically stores the exception pointer `p` into the shared state and makes the state ready. The operation behaves as though `[set\_value](set_value "cpp/thread/promise/set value")`, `set_exception`, `[set\_value\_at\_thread\_exit](set_value_at_thread_exit "cpp/thread/promise/set value at thread exit")`, and `[set\_exception\_at\_thread\_exit](set_exception_at_thread_exit "cpp/thread/promise/set exception at thread exit")` acquire a single mutex associated with the promise object while updating the promise object. An exception is thrown if there is no shared state or the shared state already stores a value or exception. Calls to this function do not introduce data races with calls to `[get\_future](get_future "cpp/thread/promise/get future")` (therefore they need not synchronize with each other). ### Parameters | | | | | --- | --- | --- | | p | - | exception pointer to store. The behavior is undefined if `p` is null. | ### Return value (none). ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following conditions: * `*this` has no shared state. The error code is set to [`no_state`](../future_errc "cpp/thread/future errc"). * The shared state already stores a value or exception. The error code is set to [`promise_already_satisfied`](../future_errc "cpp/thread/future errc"). ### Example ``` #include <thread> #include <iostream> #include <future> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p]{ try { // code that may throw throw std::runtime_error("Example"); } catch(...) { try { // store anything thrown in the promise p.set_exception(std::current_exception()); // or throw a custom exception instead // p.set_exception(std::make_exception_ptr(MyException("mine"))); } catch(...) {} // set_exception() may throw too } }); try { std::cout << f.get(); } catch(const std::exception& e) { std::cout << "Exception from the thread: " << e.what() << '\n'; } t.join(); } ``` Output: ``` Exception from the thread: Example ``` ### See also | | | | --- | --- | | [set\_exception\_at\_thread\_exit](set_exception_at_thread_exit "cpp/thread/promise/set exception at thread exit") | sets the result to indicate an exception while delivering the notification only at thread exit (public member function) | cpp std::promise<R>::set_value std::promise<R>::set\_value =========================== | | | | | --- | --- | --- | | ``` void set_value( const R& value ); ``` | (1) | (member only of generic `promise` template)(since C++11) | | ``` void set_value( R&& value ); ``` | (2) | (member only of generic `promise` template)(since C++11) | | ``` void set_value( R& value ); ``` | (3) | (member only of `promise<R&>` template specialization)(since C++11) | | ``` void set_value(); ``` | (4) | (member only of `promise<void>` template specialization)(since C++11) | 1-3) Atomically stores the `value` into the shared state and makes the state ready. 4) Makes the state ready The operation behaves as though `set_value`, `[set\_exception](set_exception "cpp/thread/promise/set exception")`, `[set\_value\_at\_thread\_exit](set_value_at_thread_exit "cpp/thread/promise/set value at thread exit")`, and `[set\_exception\_at\_thread\_exit](set_exception_at_thread_exit "cpp/thread/promise/set exception at thread exit")` acquire a single mutex associated with the promise object while updating the promise object. An exception is thrown if there is no shared state or the shared state already stores a value or exception. Calls to this function do not introduce data races with calls to `[get\_future](get_future "cpp/thread/promise/get future")` (therefore they need not synchronize with each other). ### Parameters | | | | | --- | --- | --- | | value | - | value to store in the shared state | ### Return value (none). ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following conditions: * `*this` has no shared state. The error code is set to [`no_state`](../future_errc "cpp/thread/future errc"). * The shared state already stores a value or exception. The error code is set to [`promise_already_satisfied`](../future_errc "cpp/thread/future errc"). Additionally: 1) Any exception thrown by the copy constructor of `value` 2) Any exception thrown by the move constructor of `value` ### Example This example shows how `[std::promise](http://en.cppreference.com/w/cpp/thread/promise)<void>` can be used as signals between threads. ``` #include <thread> #include <future> #include <cctype> #include <vector> #include <algorithm> #include <iterator> #include <iostream> #include <sstream> #include <chrono> using namespace std::chrono_literals; int main() { std::istringstream iss_numbers{"3 4 1 42 23 -23 93 2 -289 93"}; std::istringstream iss_letters{" a 23 b,e a2 k k?a;si,ksa c"}; std::vector<int> numbers; std::vector<char> letters; std::promise<void> numbers_promise, letters_promise; auto numbers_ready = numbers_promise.get_future(); auto letter_ready = letters_promise.get_future(); std::thread value_reader([&] { // I/O operations. std::copy(std::istream_iterator<int>{iss_numbers}, std::istream_iterator<int>{}, std::back_inserter(numbers)); // Notify for numbers. numbers_promise.set_value(); std::copy_if(std::istreambuf_iterator<char>{iss_letters}, std::istreambuf_iterator<char>{}, std::back_inserter(letters), ::isalpha); // Notify for letters. letters_promise.set_value(); }); numbers_ready.wait(); std::sort(numbers.begin(), numbers.end()); if (letter_ready.wait_for(1s) == std::future_status::timeout) { // Output the numbers while letters are being obtained. for (int num : numbers) std::cout << num << ' '; numbers.clear(); // Numbers were already printed. } letter_ready.wait(); std::sort(letters.begin(), letters.end()); // If numbers were already printed, it does nothing. for (int num : numbers) std::cout << num << ' '; std::cout << '\n'; for (char let : letters) std::cout << let << ' '; std::cout << '\n'; value_reader.join(); } ``` Output: ``` -289 -23 1 2 3 4 23 42 93 93 a a a a b c e i k k k s s ``` ### See also | | | | --- | --- | | [set\_exception](set_exception "cpp/thread/promise/set exception") | sets the result to indicate an exception (public member function) | cpp std::promise<R>::promise std::promise<R>::promise ======================== | | | | | --- | --- | --- | | ``` promise(); ``` | (1) | (since C++11) | | ``` template< class Alloc > promise( std::allocator_arg_t, const Alloc& alloc ); ``` | (2) | (since C++11) | | ``` promise( promise&& other ) noexcept; ``` | (3) | (since C++11) | | ``` promise( const promise& other ) = delete; ``` | (4) | (since C++11) | Constructs a `promise` object. 1) Default constructor. Constructs the promise with an empty shared state. 2) Constructs the promise with an empty shared state. The shared state is allocated using `alloc`. `Alloc` must meet the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). 3) Move constructor. Constructs the promise with the shared state of `other` using move semantics. After construction, `other` has no shared state. 4) `promise` is not copyable. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use to allocate the shared state | | other | - | another `promise` to acquire the state from | ### Exceptions 1-2) May throw implementation-defined exceptions. ### Example cpp std::promise<R>::swap std::promise<R>::swap ===================== | | | | | --- | --- | --- | | ``` void swap( promise& other ) noexcept; ``` | | (since C++11) | Exchanges the shared states of two promise objects. ### Parameters | | | | | --- | --- | --- | | other | - | the promise to swap with | ### Return value (none). ### Example ### See also | | | | --- | --- | | [std::swap(std::promise)](swap2 "cpp/thread/promise/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::promise<R>::set_exception_at_thread_exit std::promise<R>::set\_exception\_at\_thread\_exit ================================================= | | | | | --- | --- | --- | | ``` void set_exception_at_thread_exit( std::exception_ptr p ); ``` | | (since C++11) | Stores the exception pointer `p` into the shared state without making the state ready immediately. The state is made ready when the current thread exits, after all variables with thread-local storage duration have been destroyed. The operation behaves as though `[set\_value](set_value "cpp/thread/promise/set value")`, `[set\_exception](set_exception "cpp/thread/promise/set exception")`, `[set\_value\_at\_thread\_exit](set_value_at_thread_exit "cpp/thread/promise/set value at thread exit")`, and `set_exception_at_thread_exit` acquire a single mutex associated with the promise object while updating the promise object. An exception is thrown if there is no shared state or the shared state already stores a value or exception. Calls to this function do not introduce data races with calls to `[get\_future](get_future "cpp/thread/promise/get future")` (therefore they need not synchronize with each other). ### Parameters | | | | | --- | --- | --- | | p | - | exception pointer to store. The behavior is undefined if `p` is `nullptr`. | ### Return value (none). ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following conditions: * `*this` has no shared state. The error code is set to [`no_state`](../future_errc "cpp/thread/future errc"). * The shared state already stores a value or exception. The error code is set to [`promise_already_satisfied`](../future_errc "cpp/thread/future errc"). ### Example ### See also | | | | --- | --- | | [set\_exception](set_exception "cpp/thread/promise/set exception") | sets the result to indicate an exception (public member function) |
programming_docs
cpp std::promise<R>::set_value_at_thread_exit std::promise<R>::set\_value\_at\_thread\_exit ============================================= | | | | | --- | --- | --- | | ``` void set_value_at_thread_exit( const R& value ); ``` | (1) | (member only of generic `promise` template)(since C++11) | | ``` void set_value_at_thread_exit( R&& value ); ``` | (2) | (member only of generic `promise` template)(since C++11) | | ``` void set_value_at_thread_exit( R& value ); ``` | (3) | (member only of `promise<R&>` template specialization)(since C++11) | | ``` void set_value_at_thread_exit() ``` | (4) | (member only of `promise<void>` template specialization)(since C++11) | Stores the `value` into the shared state without making the state ready immediately. The state is made ready when the current thread exits, after all variables with thread-local storage duration have been destroyed. The operation behaves as though `[set\_value](set_value "cpp/thread/promise/set value")`, `[set\_exception](set_exception "cpp/thread/promise/set exception")`, `set_value_at_thread_exit`, and `[set\_exception\_at\_thread\_exit](set_exception_at_thread_exit "cpp/thread/promise/set exception at thread exit")` acquire a single mutex associated with the promise object while updating the promise object. An exception is thrown if there is no shared state or the shared state already stores a value or exception. Calls to this function do not introduce data races with calls to `[get\_future](get_future "cpp/thread/promise/get future")` (therefore they need not synchronize with each other). ### Parameters | | | | | --- | --- | --- | | value | - | value to store in the shared state | ### Return value (none). ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following conditions: * `*this` has no shared state. The error code is set to [`no_state`](../future_errc "cpp/thread/future errc"). * The shared state already stores a value or exception. The error code is set to [`promise_already_satisfied`](../future_errc "cpp/thread/future errc"). Additionally: 1-2) Any exception thrown by the copy constructor of `value` 3) Any exception thrown by the move constructor of `value` ### Example ``` #include <iostream> #include <future> #include <thread> int main() { using namespace std::chrono_literals; std::promise<int> p; std::future<int> f = p.get_future(); std::thread([&p] { std::this_thread::sleep_for(1s); p.set_value_at_thread_exit(9); }).detach(); std::cout << "Waiting..." << std::flush; f.wait(); std::cout << "Done!\nResult is: " << f.get() << '\n'; } ``` Output: ``` Waiting...Done! Result is: 9 ``` ### See also | | | | --- | --- | | [set\_value](set_value "cpp/thread/promise/set value") | sets the result to specific value (public member function) | cpp std::promise<R>::get_future std::promise<R>::get\_future ============================ | | | | | --- | --- | --- | | ``` std::future<R> get_future(); ``` | | (since C++11) | Returns a future object associated with the same shared state as `*this`. An exception is thrown if `*this` has no shared state or `get_future` has already been called. To get multiple "pop" ends of the promise-future communication channel, use `[std::future::share](../future/share "cpp/thread/future/share")`. Calls to this function do not introduce data races with calls to `[set\_value](set_value "cpp/thread/promise/set value")`, `[set\_exception](set_exception "cpp/thread/promise/set exception")`, `[set\_value\_at\_thread\_exit](set_value_at_thread_exit "cpp/thread/promise/set value at thread exit")`, or `[set\_exception\_at\_thread\_exit](set_exception_at_thread_exit "cpp/thread/promise/set exception at thread exit")` (but they need not synchronize with each other). ### Parameters (none). ### Return value A future referring to the shared state of `*this`. ### Exceptions `[std::future\_error](../future_error "cpp/thread/future error")` on the following conditions: * `*this` has no shared state. The error category is set to [`no_state`](../future_errc "cpp/thread/future errc"). * `get_future()` has already been called on a promise with the same shared state as `*this`. The error category is set to [`future_already_retrieved`](../future_errc "cpp/thread/future errc"). cpp std::swap(std::promise) std::swap(std::promise) ======================= | Defined in header `[<future>](../../header/future "cpp/header/future")` | | | | --- | --- | --- | | ``` template< class R > void swap( promise<R> &lhs, promise<R> &rhs ) noexcept; ``` | | (since C++11) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::promise](../promise "cpp/thread/promise")`. Exchanges the shared state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | promises whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/thread/promise/swap") | swaps two promise objects (public member function) | cpp std::promise<R>::operator= std::promise<R>::operator= ========================== | | | | | --- | --- | --- | | ``` promise& operator=( promise&& other ) noexcept; ``` | (1) | (since C++11) | | ``` promise& operator=( const promise& rhs ) = delete; ``` | (2) | (since C++11) | Assigns the contents. 1) Move assignment operator. First, abandons the shared state (as in `~promise()`), then assigns the shared state of `other` as if by executing `[std::promise](http://en.cppreference.com/w/cpp/thread/promise)(std::move(other)).swap(\*this)`. 2) `promise` is not copy-assignable. ### Parameters | | | | | --- | --- | --- | | other | - | another `promise` to acquire the state from | ### Return value `*this`. cpp std::lock_guard<Mutex>::lock_guard std::lock\_guard<Mutex>::lock\_guard ==================================== | | | | | --- | --- | --- | | ``` explicit lock_guard( mutex_type& m ); ``` | (1) | (since C++11) | | ``` lock_guard( mutex_type& m, std::adopt_lock_t t ); ``` | (2) | (since C++11) | | ``` lock_guard( const lock_guard& ) = delete; ``` | (3) | (since C++11) | Acquires ownership of the given mutex `m`. 1) Effectively calls `m.lock()`. 2) Acquires ownership of the mutex `m` without attempting to lock it. The behavior is undefined if the current thread does not hold a non-shared lock (i.e., a lock acquired by `lock`, `try_lock`, `try_lock_for`, or `try_lock_until`) on `m`. 3) Copy constructor is deleted. The behavior is undefined if `m` is destroyed before the `lock_guard` object is. ### Parameters | | | | | --- | --- | --- | | m | - | mutex to acquire ownership of. | | t | - | tag parameter used to select non-locking version of the constructor. | ### Exceptions 1) Throws any exceptions thrown by `m.lock()`. 2) Throws nothing. cpp std::lock_guard<Mutex>::~lock_guard std::lock\_guard<Mutex>::~lock\_guard ===================================== | | | | | --- | --- | --- | | ``` ~lock_guard(); ``` | | (since C++11) | Releases the ownership of the owned mutex. Effectively calls `m.unlock()` where `m` is the mutex passed to the `lock_guard`'s constructor. cpp std::mutex::mutex std::mutex::mutex ================= | | | | | --- | --- | --- | | ``` constexpr mutex() noexcept; ``` | (1) | (since C++11) | | ``` mutex( const mutex& ) = delete; ``` | (2) | (since C++11) | 1) Constructs the mutex. The mutex is in unlocked state after the constructor completes. 2) Copy constructor is deleted. ### Parameters (none). ### Notes Because the default constructor is `constexpr`, static mutexes are initialized as part of [static non-local initialization](../../language/initialization#Non-local_variables "cpp/language/initialization"), before any dynamic non-local initialization begins. This makes it safe to lock a mutex in a constructor of any static object. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_init "c/thread/mtx init") for `mtx_init` | cpp std::mutex::unlock std::mutex::unlock ================== | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++11) | Unlocks the mutex. The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent lock operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); int g_num_running = ++g_num; g_num_mutex.unlock(); std::cout << id << " => " << g_num_running << '\n'; std::this_thread::sleep_for(std::chrono::seconds(1)); } } int main() { std::thread t1(slow_increment, 0); std::thread t2(slow_increment, 1); t1.join(); t2.join(); } ``` Possible output: ``` 0 => 1 1 => 2 0 => 3 1 => 4 0 => 5 1 => 6 ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_unlock "c/thread/mtx unlock") for `mtx_unlock` | cpp std::mutex::~mutex std::mutex::~mutex ================== | | | | | --- | --- | --- | | ``` ~mutex(); ``` | | | Destroys the mutex. The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_destroy "c/thread/mtx destroy") for `mtx_destroy` | cpp std::mutex::try_lock std::mutex::try\_lock ===================== | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++11) | Tries to lock the mutex. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currently locked by any other thread. If `try_lock` is called by a thread that already owns the `mutex`, the behavior is undefined. Prior `[unlock()](unlock "cpp/thread/mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. Note that prior `[lock()](lock "cpp/thread/mutex/lock")` does not synchronize with this operation if it returns `false`. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ``` #include <chrono> #include <mutex> #include <thread> #include <iostream> // std::cout std::chrono::milliseconds interval(100); std::mutex mutex; int job_shared = 0; // both threads can modify 'job_shared', // mutex will protect this variable int job_exclusive = 0; // only one thread can modify 'job_exclusive' // no protection needed // this thread can modify both 'job_shared' and 'job_exclusive' void job_1() { std::this_thread::sleep_for(interval); // let 'job_2' take a lock while (true) { // try to lock mutex to modify 'job_shared' if (mutex.try_lock()) { std::cout << "job shared (" << job_shared << ")\n"; mutex.unlock(); return; } else { // can't get lock to modify 'job_shared' // but there is some other work to do ++job_exclusive; std::cout << "job exclusive (" << job_exclusive << ")\n"; std::this_thread::sleep_for(interval); } } } // this thread can modify only 'job_shared' void job_2() { mutex.lock(); std::this_thread::sleep_for(5 * interval); ++job_shared; mutex.unlock(); } int main() { std::thread thread_1(job_1); std::thread thread_2(job_2); thread_1.join(); thread_2.join(); } ``` Possible output: ``` job exclusive (1) job exclusive (2) job exclusive (3) job exclusive (4) job shared (1) ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_trylock "c/thread/mtx trylock") for `mtx_trylock` | cpp std::mutex::native_handle std::mutex::native\_handle ========================== | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++11) (not always present) | Returns the underlying implementation-defined native handle object. ### Parameters (none). ### Return value Implementation-defined native handle object. ### Exceptions Implementation-defined. ### Example cpp std::mutex::lock std::mutex::lock ================ | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++11) | Locks the mutex. If another thread has already locked the mutex, a call to `lock` will block execution until the lock is acquired. If `lock` is called by a thread that already owns the `mutex`, the behavior is undefined: for example, the program *may* deadlock. An implementation that can detect the invalid usage is encouraged to throw a `[std::system\_error](../../error/system_error "cpp/error/system error")` with error condition `resource_deadlock_would_occur` instead of deadlocking. Prior `[unlock()](unlock "cpp/thread/mutex/unlock")` operations on the same mutex *synchronize-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`, [`std::scoped_lock`](../scoped_lock "cpp/thread/scoped lock"), and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); ++g_num; // note, that the mutex also syncronizes the output std::cout << "id: " << id << ", g_num: " << g_num << '\n'; g_num_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(234)); } } int main() { std::thread t1{slow_increment, 0}; std::thread t2{slow_increment, 1}; t1.join(); t2.join(); } ``` Possible output: ``` id: 0, g_num: 1 id: 1, g_num: 2 id: 1, g_num: 3 id: 0, g_num: 4 id: 0, g_num: 5 id: 1, g_num: 6 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_lock "c/thread/mtx lock") for `mtx_lock` | cpp std::jthread::join std::jthread::join ================== | | | | | --- | --- | --- | | ``` void join(); ``` | | (since C++20) | Blocks the current thread until the thread identified by `*this` finishes its execution. The completion of the thread identified by `*this` *synchronizes with* the corresponding successful return from `join()`. No synchronization is performed on `*this` itself. Concurrently calling `join()` on the same jthread object from multiple threads constitutes a data race that results in undefined behavior. ### Parameters (none). ### Return value (none). ### Postconditions `joinable()` is `false`. ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if an error occurs. ### Error Conditions * `[resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` if `this->get_id() == [std::this\_thread::get\_id](http://en.cppreference.com/w/cpp/thread/get_id)()` (deadlock detected) * `[no\_such\_process](../../error/errc "cpp/error/errc")` if the thread is not valid * `[invalid\_argument](../../error/errc "cpp/error/errc")` if `joinable()` is `false` ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { // simulate expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { // simulate expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::cout << "starting first helper...\n"; std::jthread helper1(foo); std::cout << "starting second helper...\n"; std::jthread helper2(bar); std::cout << "waiting for helpers to finish..." << std::endl; helper1.join(); helper2.join(); std::cout << "done!\n"; } ``` Output: ``` starting first helper... starting second helper... waiting for helpers to finish... done! ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.3.2 Members [thread.jthread.mem] ### See also | | | | --- | --- | | [detach](detach "cpp/thread/jthread/detach") | permits the thread to execute independently from the thread handle (public member function) | | [joinable](joinable "cpp/thread/jthread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_join "c/thread/thrd join") for `thrd_join` | cpp std::jthread::get_stop_token std::jthread::get\_stop\_token ============================== | | | | | --- | --- | --- | | ``` std::stop_token get_stop_token() const noexcept; ``` | | (since C++20) | Returns a `[std::stop\_token](../stop_token "cpp/thread/stop token")` associated with the same shared stop-state held internally by the `jthread` object. ### Parameters (none). ### Return value A value of type `[std::stop\_token](../stop_token "cpp/thread/stop token")` associated with stop-state held internally by `jthread` object. ### Example cpp std::jthread::~jthread std::jthread::~jthread ====================== | | | | | --- | --- | --- | | ``` ~jthread(); ``` | | (since C++20) | Destroys the `jthread` object. If `*this` has an associated thread (`joinable() == true`), calls `request_stop()` and then `join()`. ### Notes The `request_stop()` has no effect if the `jthread` was previously requested to stop. A `jthread` object does not have an associated thread after. * it was default-constructed * it was moved from * `join()` has been called * `detach()` has been called If `join()` throws an exception (e.g. because deadlock is detected), `[std::terminate()](../../error/terminate "cpp/error/terminate")` may be called.
programming_docs
cpp std::jthread::get_stop_source std::jthread::get\_stop\_source =============================== | | | | | --- | --- | --- | | ``` std::stop_source get_stop_source() noexcept; ``` | | (since C++20) | Returns a `[std::stop\_source](../stop_source "cpp/thread/stop source")` associated with the same shared stop-state as held internally by the `jthread` object. ### Parameters (none). ### Return value A value of type `[std::stop\_source](../stop_source "cpp/thread/stop source")` associated with stop-state held internally by `jthread` object. ### Example cpp std::jthread::request_stop std::jthread::request\_stop =========================== | | | | | --- | --- | --- | | ``` bool request_stop() noexcept; ``` | | (since C++20) | Issues a stop request to the internal stop-state, if it has not yet already had stop requested. The determination is made atomically, and if stop was requested, the stop-state is atomically updated to avoid race conditions, such that: * `stop_requested()` and `stop_possible()` can be concurrently invoked on other `[std::stop\_token](../stop_token "cpp/thread/stop token")`s and `[std::stop\_source](../stop_source "cpp/thread/stop source")`s of the same shared stop-state * `request_stop()` can be concurrently invoked from multiple threads on the same `jthread` object or on other `[std::stop\_source](../stop_source "cpp/thread/stop source")` objects associated with the same stop-state, and only one will actually perform the stop request However, see the Notes section. ### Parameters (none). ### Return value `true` if this invocation made a stop request, otherwise `false`. ### Postconditions For a `[std::stop\_token](../stop_token "cpp/thread/stop token")` retrieved by `get_stop_token()` or a `[std::stop\_source](../stop_source "cpp/thread/stop source")` retrieved by `get_stop_source()`, `stop_requested()` is `true`. ### Notes If the `request_stop()` does issue a stop request (i.e., returns `true`), then any `std::stop_callbacks` registered for the same associated stop-state will be invoked synchronously, on the same thread `request_stop()` is issued on. If an invocation of a callback exits via an exception, `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. If a stop request has already been made, this function returns `false`. However there is no guarantee that another thread or `[std::stop\_source](../stop_source "cpp/thread/stop source")` object which has just (successfully) requested stop for the same stop-state is not still in the middle of invoking a `[std::stop\_callback](../stop_callback "cpp/thread/stop callback")` function. If the `request_stop()` does issue a stop request (i.e., returns `true`), then all condition variables of base type `[std::condition\_variable\_any](../condition_variable_any "cpp/thread/condition variable any")` registered with an interruptible wait for `[std::stop\_token](../stop_token "cpp/thread/stop token")`s associated with the `jthread`'s internal stop-state will be awoken. ### Example ``` #include <iostream> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> using namespace std::chrono_literals; int main() { // A sleepy worker thread std::jthread sleepy_worker([](std::stop_token stoken) { for (int i = 10; i; --i) { std::this_thread::sleep_for(300ms); if (stoken.stop_requested()) { std::cout << "Sleepy worker is requested to stop\n"; return; } std::cout << "Sleepy worker goes back to sleep\n"; } }); // A waiting worker thread // The condition variable will be awoken by the stop request. std::jthread waiting_worker([](std::stop_token stoken) { std::mutex mutex; std::unique_lock lock(mutex); std::condition_variable_any().wait(lock, stoken, [&stoken] { return false; }); if (stoken.stop_requested()) { std::cout << "Waiting worker is requested to stop\n"; return; } }); // std::jthread::request_stop() can be called explicitly: std::cout << "Requesting stop of sleepy worker\n"; sleepy_worker.request_stop(); sleepy_worker.join(); std::cout << "Sleepy worker joined\n"; // Or automatically using RAII: // waiting_worker's destructor will call request_stop() // and join the thread automatically. } ``` Possible output: ``` Requesting stop of sleepy worker Sleepy worker is requested to stop Sleepy worker joined Waiting worker is requested to stop ``` cpp std::jthread::swap std::jthread::swap ================== | | | | | --- | --- | --- | | ``` void swap( std::jthread& other ) noexcept; ``` | | (since C++20) | Exchanges the underlying handles of two jthread objects. ### Parameters | | | | | --- | --- | --- | | other | - | the jthread to swap with | ### Return value (none). ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::jthread t1(foo); std::jthread t2(bar); std::cout << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; std::swap(t1, t2); std::cout << "after std::swap(t1, t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.swap(t2); std::cout << "after t1.swap(t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; } ``` Possible output: ``` thread 1 id: 140185268262656 thread 2 id: 140185259869952 after std::swap(t1, t2): thread 1 id: 140185259869952 thread 2 id: 140185268262656 after t1.swap(t2): thread 1 id: 140185268262656 thread 2 id: 140185259869952 ``` ### See also | | | | --- | --- | | [swap(std::jthread)](swap2 "cpp/thread/jthread/swap2") (C++20) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | cpp std::jthread::detach std::jthread::detach ==================== | | | | | --- | --- | --- | | ``` void detach(); ``` | | (since C++20) | Separates the thread of execution from the jthread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. After calling `detach` `*this` no longer owns any thread. ### Parameters (none). ### Return value (none). ### Postconditions `joinable` is `false`. ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if `joinable() == false` or an error occurs. ### Example ``` #include <iostream> #include <chrono> #include <thread> void independentThread() { std::cout << "Starting concurrent thread.\n"; std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "Exiting concurrent thread.\n"; } void threadCaller() { std::cout << "Starting thread caller.\n"; std::jthread t(independentThread); t.detach(); std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "Exiting thread caller.\n"; } int main() { threadCaller(); std::this_thread::sleep_for(std::chrono::seconds(5)); } ``` Possible output: ``` Starting thread caller. Starting concurrent thread. Exiting thread caller. Exiting concurrent thread. ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.3.2 Members [thread.jthread.mem] ### See also | | | | --- | --- | | [join](join "cpp/thread/jthread/join") | waits for the thread to finish its execution (public member function) | | [joinable](joinable "cpp/thread/jthread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_detach "c/thread/thrd detach") for `thrd_detach` | cpp swap(std::jthread) swap(std::jthread) ================== | | | | | --- | --- | --- | | ``` friend void swap( jthread &lhs, jthread &rhs ) noexcept; ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::jthread](../jthread "cpp/thread/jthread")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. 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::jthread` is an associated class of the arguments. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | jthreads whose states to swap | ### Return value (none). ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { using std::swap; std::jthread t1(foo); std::jthread t2(bar); std::cout << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; swap(t1, t2); std::cout << "after std::swap(t1, t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.swap(t2); std::cout << "after t1.swap(t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; } ``` Possible output: ``` thread 1 id: 1892 thread 2 id: 2584 after std::swap(t1, t2): thread 1 id: 2584 thread 2 id: 1892 after t1.swap(t2): thread 1 id: 1892 thread 2 id: 2584 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/thread/jthread/swap") | swaps two jthread objects (public member function) | cpp std::jthread::hardware_concurrency std::jthread::hardware\_concurrency =================================== | | | | | --- | --- | --- | | ``` [[nodiscard]] static unsigned int hardware_concurrency() noexcept; ``` | | (since C++20) | Returns the number of concurrent threads supported by the implementation. The value should be considered only a hint. ### Parameters (none). ### Return value Number of concurrent threads supported. If the value is not well defined or not computable, returns `​0​`. ### Example ``` #include <iostream> #include <thread> int main() { unsigned int n = std::jthread::hardware_concurrency(); std::cout << n << " concurrent threads are supported.\n"; } ``` Possible output: ``` 4 concurrent threads are supported. ``` ### See also | | | | --- | --- | | [hardware\_destructive\_interference\_sizehardware\_constructive\_interference\_size](../hardware_destructive_interference_size "cpp/thread/hardware destructive interference size") (C++17) | min offset to avoid false sharingmax offset to promote true sharing (constant) | cpp std::jthread::get_id std::jthread::get\_id ===================== | | | | | --- | --- | --- | | ``` [[nodiscard]] std::jthread::id get_id() const noexcept; ``` | | (since C++20) | Returns a value of `std::jthread::id` identifying the thread associated with `*this`. ### Parameters (none). ### Return value A value of type `std::jthread::id` identifying the thread associated with `*this`. If there is no thread associated, default constructed `std::jthread::id` is returned. ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::jthread t1(foo); std::jthread::id t1_id = t1.get_id(); std::jthread t2(foo); std::jthread::id t2_id = t2.get_id(); std::cout << "t1's id: " << t1_id << '\n'; std::cout << "t2's id: " << t2_id << '\n'; } ``` Possible output: ``` t1's id: 0x35a7210f t2's id: 0x35a311c4 ``` ### See also | | | | --- | --- | | [id](../thread/id "cpp/thread/thread/id") | represents the *id* of a thread (public member class of `std::thread`) | | [joinable](joinable "cpp/thread/jthread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | cpp std::jthread::operator= std::jthread::operator= ======================= | | | | | --- | --- | --- | | ``` std::jthread& operator=( std::jthread&& other ) noexcept; ``` | | (since C++20) | If `*this` still has an associated running thread (i.e. `joinable() == true`), calls `request_stop()` followed by `join()`. Assigns the state of `other` to `*this` and sets `other` to a default constructed state. After this call, `this->get_id()` is equal to the value of `other.get_id()` prior to the call and the associated stop-state is also moved, and `other` no longer represents a thread of execution nor has any stop-state. ### Parameters | | | | | --- | --- | --- | | other | - | another `jthread` object to assign to this `jthread` object | ### Return value `*this`. cpp std::jthread::joinable std::jthread::joinable ====================== | | | | | --- | --- | --- | | ``` [[nodiscard]] bool joinable() const noexcept; ``` | | (since C++20) | Checks if the `std::jthread` object identifies an active thread of execution. Specifically, returns `true` if `get_id() != std::jthread::id()`. So a default constructed jthread is not joinable. A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable. ### Parameters (none). ### Return value `true` if the jthread object identifies an active thread of execution, `false` otherwise. ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::jthread t; std::cout << "before starting, joinable: " << std::boolalpha << t.joinable() << '\n'; t = std::jthread(foo); std::cout << "after starting, joinable: " << t.joinable() << '\n'; t.join(); std::cout << "after joining, joinable: " << t.joinable() << '\n'; } ``` Output: ``` before starting, joinable: false after starting, joinable: true after joining, joinable: false ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.3.2 Members [thread.jthread.mem] ### See also | | | | --- | --- | | [get\_id](get_id "cpp/thread/jthread/get id") | returns the *id* of the thread (public member function) | | [join](join "cpp/thread/jthread/join") | waits for the thread to finish its execution (public member function) | | [detach](detach "cpp/thread/jthread/detach") | permits the thread to execute independently from the thread handle (public member function) | cpp std::jthread::native_handle std::jthread::native\_handle ============================ | | | | | --- | --- | --- | | ``` [[nodiscard]] native_handle_type native_handle(); ``` | | (since C++20) (not always present) | Returns the implementation defined underlying thread handle. ### Parameters (none). ### Return value implementation defined handle type representing the thread. ### Exceptions May throw implementation-defined exceptions. ### Example Uses `native_handle` to enable realtime scheduling of C++ threads on a POSIX system. ``` #include <thread> #include <mutex> #include <iostream> #include <chrono> #include <cstring> #include <pthread.h> std::mutex iomutex; void f(int num) { std::this_thread::sleep_for(std::chrono::seconds(1)); sched_param sch; int policy; pthread_getschedparam(pthread_self(), &policy, &sch); std::lock_guard<std::mutex> lk(iomutex); std::cout << "Thread " << num << " is executing at priority " << sch.sched_priority << '\n'; } int main() { std::jthread t1(f, 1), t2(f, 2); sched_param sch; int policy; pthread_getschedparam(t1.native_handle(), &policy, &sch); sch.sched_priority = 20; if (pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch)) { std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n'; } } ``` Output: ``` Thread 2 is executing at priority 0 Thread 1 is executing at priority 20 ``` cpp std::future_error::future_error std::future\_error::future\_error ================================= | | | | | --- | --- | --- | | ``` future_error( const future_error& other ) noexcept; ``` | (1) | (since C++11) | | ``` explicit future_error( std::future_errc ec ); ``` | (2) | (since C++17) | 1) Copy constructor. Initializes the contents of the new `future_error` object with those of `other`. If `*this` and `other` both have dynamic type `std::future_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. 2) Constructs a new `future_error` object containing the error code `std::make_error_code(ec)`. ### Parameters | | | | | --- | --- | --- | | other | - | another `future_error` object to copy | | ec | - | error code | ### Notes There is no standard-compliant way for the user to construct a `future_error` other than copying from another `future_error` prior to C++17. C++11 and C++14 depict an exposition-only public constructor taking a `[std::error\_code](../../error/error_code "cpp/error/error code")`, and some implementations provide such a constructor. cpp std::future_error::operator= std::future\_error::operator= ============================= | | | | | --- | --- | --- | | ``` future_error& operator=( const future_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::future_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another `future_error` object to assign with | ### Return value `*this`. ### Example cpp std::future_error::code std::future\_error::code ======================== | | | | | --- | --- | --- | | ``` const std::error_code& code() const noexcept; ``` | | (since C++11) | Returns the stored error code. ### Parameters (none). ### Return value The stored error code. ### See also | | | | --- | --- | | [what](what "cpp/thread/future error/what") | returns the explanatory string specific to the error code (public member function) | cpp std::future_error::what std::future\_error::what ======================== | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. ### See also | | | | --- | --- | | [code](code "cpp/thread/future error/code") | returns the error code (public member function) | cpp std::stop_token::~stop_token std::stop\_token::~stop\_token ============================== | | | | | --- | --- | --- | | ``` ~stop_token(); ``` | | (since C++20) | Destroys the `stop_token` object. If `*this` has associated stop-state, releases ownership of it. cpp std::stop_token::swap std::stop\_token::swap ====================== | | | | | --- | --- | --- | | ``` void swap( std::stop_token& other ) noexcept; ``` | | (since C++20) | Exchanges the associated stop-state of `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | `stop_token` to exchange the contents with | ### Return value (none).
programming_docs
cpp std::stop_token::stop_requested std::stop\_token::stop\_requested ================================= | | | | | --- | --- | --- | | ``` [[nodiscard]] bool stop_requested() const noexcept; ``` | | (since C++20) | Checks if the `stop_token` object has associated stop-state and that state has received a stop request. A default constructed `stop_token` has no associated stop-state, and thus has not had stop requested. ### Parameters (none). ### Return value `true` if the `stop_token` object has associated stop-state and it received a stop request, `false` otherwise. ### Example cpp std::stop_token::stop_token std::stop\_token::stop\_token ============================= | | | | | --- | --- | --- | | ``` stop_token() noexcept; ``` | (1) | (since C++20) | | ``` stop_token( const stop_token& other ) noexcept; ``` | (2) | (since C++20) | | ``` stop_token( stop_token&& other ) noexcept; ``` | (3) | (since C++20) | Constructs a new `stop_token` object. 1) Constructs an empty `stop_token` with no associated stop-state. 2) Copy constructor. Constructs a `stop_token` whose associated stop-state is the same as that of `other`. 3) Move constructor. Constructs a `stop_token` whose associated stop-state is the same as that of `other`; `other` is left empty. ### Parameters | | | | | --- | --- | --- | | other | - | another `stop_token` object to construct this `stop_token` object with | ### Postconditions 1) `stop_possible()` and `stop_requested()` are both `false` 2) `*this` and `other` share the same associated stop-state and compare equal 3) `*this` has `other`'s previously associated stop-state, and `other.stop_possible()` is `false` cpp swap(std::stop_token) swap(std::stop\_token) ====================== | | | | | --- | --- | --- | | ``` friend void swap( stop_token &lhs, stop_token &rhs ) noexcept; ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::stop\_token](../stop_token "cpp/thread/stop token")`. Exchanges the associated stop-state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. 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::stop_token` is an associated class of the arguments. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `stop_token`s to swap | ### Return value (none). cpp std::stop_token::operator= std::stop\_token::operator= =========================== | | | | | --- | --- | --- | | ``` std::stop_token& operator=( const std::stop_token& other ) noexcept; ``` | (1) | (since C++20) | | ``` std::stop_token& operator=( std::stop_token&& other ) noexcept; ``` | (2) | (since C++20) | Replaces the associated stop-state with that of `other`. 1) Copy-assigns the associated stop-state of `other` to that of `*this`. Equivalent to `stop_token(other).swap(*this)`. 2) Move-assigns the associated stop-state of `other` to that of `*this`. After the assignment, `*this` contains the previous associated stop-state of `other`, and `other` has no associated stop-state. Equivalent to `stop_token(std::move(other)).swap(*this)`. ### Parameters | | | | | --- | --- | --- | | other | - | another `stop_token` object to share the stop-state with to or acquire the stop-state from | cpp std::stop_token::stop_possible std::stop\_token::stop\_possible ================================ | | | | | --- | --- | --- | | ``` [[nodiscard]] bool stop_possible() const noexcept; ``` | | (since C++20) | Checks if the `stop_token` object has associated stop-state, and that state either has already had a stop requested or it has associated `[std::stop\_source](../stop_source "cpp/thread/stop source")` object(s). A default constructed `stop_token` has no associated stop-state, and thus cannot be stopped; the associated stop-state for which no `[std::stop\_source](../stop_source "cpp/thread/stop source")` object(s) exist can also not be stopped if such a request has not already been made. ### Parameters (none). ### Return value `false` if the `stop_token` object has no associated stop-state, or it did not yet receive a stop request and there are no associated `[std::stop\_source](../stop_source "cpp/thread/stop source")` object(s); `true` otherwise. ### Notes If the `stop_token` object has associated stop-state and a stop request has already been made, this function still returns `true`. If the `stop_token` object has associated stop-state from a `[std::jthread](../jthread "cpp/thread/jthread")`—for example, the `stop_token` was retrieved by invoking `get_stop_token()` on a `[std::jthread](../jthread "cpp/thread/jthread")` object—then this function always returns `true`. A `[std::jthread](../jthread "cpp/thread/jthread")` always has an internal `[std::stop\_source](../stop_source "cpp/thread/stop source")` object, even if the thread's invoking function does not check it. ### Example cpp operator==(std::stop_token) operator==(std::stop\_token) ============================ | | | | | --- | --- | --- | | ``` [[nodiscard]] friend bool operator==( const stop_token& lhs, const stop_token& rhs ) noexcept; ``` | | (since C++20) | Compares two `stop_token` values. 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::stop_token` is an associated class of the arguments. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `stop_token`s to compare | ### Return value `true` if `lhs` and `rhs` have the same associated stop-state, or both have no associated stop-state, otherwise `false`. cpp std::counting_semaphore<LeastMaxValue>::acquire std::counting\_semaphore<LeastMaxValue>::acquire ================================================ | | | | | --- | --- | --- | | ``` void acquire(); ``` | | (since C++20) | Atomically decrements the internal counter by `1` if it is greater than `​0​`; otherwise blocks until it is greater than `​0​` and can successfully decrement the internal counter. ### Preconditions (none). ### Parameters (none). ### Exceptions May throw `[std::system\_error](../../error/system_error "cpp/error/system error")`. ### Example The example visualizes a concurrent work of several randomized threads when no more than N (N is the semaphore `*desired*` value) of the thread-functions are active, while the other might wait on the semaphore. ``` #include <array> #include <chrono> #include <cstddef> #include <iomanip> #include <iostream> #include <mutex> #include <random> #include <semaphore> #include <thread> #include <vector> using namespace std::literals; constexpr std::size_t max_threads{10U}; // change and see the effect constexpr std::ptrdiff_t max_sema_threads{3}; // {1} for binary semaphore std::counting_semaphore semaphore{max_sema_threads}; constexpr auto time_tick{10ms}; unsigned rnd() { static std::uniform_int_distribution<unsigned> distribution{2U, 9U}; // [delays] static std::random_device engine; static std::mt19937 noise{engine()}; return distribution(noise); } class alignas( 128 /*std::hardware_destructive_interference_size*/ ) Guide { inline static std::mutex cout_mutex; inline static std::chrono::time_point<std::chrono::high_resolution_clock> started_at; unsigned delay{rnd()}, occupy{rnd()}, wait_on_sema{}; public: static void start_time() { started_at = std::chrono::high_resolution_clock::now(); } void initial_delay() { std::this_thread::sleep_for(delay * time_tick); } void occupy_sema() { wait_on_sema = static_cast<unsigned>(std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - started_at - delay * time_tick) .count() / time_tick.count()); std::this_thread::sleep_for(occupy * time_tick); } void visualize(unsigned id, unsigned x_scale = 2) const { auto cout_n = [=] (auto str, unsigned n) { n *= x_scale; while (n-- > 0) { std::cout << str; } }; std::lock_guard lk{cout_mutex}; std::cout << "#" << std::setw(2) << id << " "; cout_n("░", delay); cout_n("▒", wait_on_sema); cout_n("█", occupy); std::cout << '\n'; } static void show_info() { std::cout << "\nThreads: " << max_threads << ", Throughput: " << max_sema_threads << " │ Legend: initial delay ░░ │ wait state ▒▒ │ sema occupation ██ \n" << std::endl; } }; std::array<Guide, max_threads> guides; void workerThread(unsigned id) { guides[id].initial_delay(); // emulate some work before sema acquisition semaphore.acquire(); // wait until a free sema slot is available guides[id].occupy_sema(); // emulate some work while sema is acquired semaphore.release(); guides[id].visualize(id); } int main() { std::vector<std::jthread> threads; threads.reserve(max_threads); Guide::show_info(); Guide::start_time(); for (auto id{0U}; id != max_threads; ++id) { threads.push_back(std::jthread(workerThread, id)); } } ``` Possible output: ``` Default case: max_threads{10U}, max_sema_threads{3} Threads: 10, Throughput: 3 │ Legend: initial delay ░░ │ wait state ▒▒ │ sema occupation ██ # 1 ░░░░██████ # 2 ░░░░████████ # 5 ░░░░░░██████████ # 8 ░░░░░░░░░░░░████████████ # 9 ░░░░░░░░░░░░██████████████ # 7 ░░░░░░░░░░░░▒▒▒▒████████████████ # 4 ░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒████████ # 6 ░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒██████████████████ # 3 ░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████████ # 0 ░░░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████████████ ────────────────────────────────────────────────────────────────────────────────────────────────────────────── "Enough for everyone" case (no wait states!): max_threads{10U}, max_sema_threads{10} Threads: 10, Throughput: 10 │ Legend: initial delay ░░ │ wait state ▒▒ │ sema occupation ██ # 4 ░░░░██████ # 5 ░░░░░░████ # 3 ░░░░██████████ # 1 ░░░░██████████ # 8 ░░░░░░░░████████████ # 6 ░░░░░░░░░░░░░░░░██████ # 7 ░░░░░░░░░░░░░░░░██████ # 9 ░░░░░░░░░░░░░░░░██████████ # 0 ░░░░░░░░░░░░██████████████████ # 2 ░░░░░░░░░░░░░░░░░░████████████ ────────────────────────────────────────────────────────────────────────────────────────────────────────────── Binary semaphore case: max_threads{10U}, max_sema_threads{1} Threads: 10, Throughput: 1 │ Legend: initial delay ░░ │ wait state ▒▒ │ sema occupation ██ # 6 ░░░░████ # 5 ░░░░▒▒▒▒████ # 4 ░░░░░░░░░░▒▒██████████ # 7 ░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒████████████████ # 2 ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████ # 3 ░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████████████ # 0 ░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████████ # 1 ░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████ # 8 ░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████ # 9 ░░░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████████████ ``` cpp std::counting_semaphore<LeastMaxValue>::try_acquire_for std::counting\_semaphore<LeastMaxValue>::try\_acquire\_for ========================================================== | | | | | --- | --- | --- | | ``` template<class Rep, class Period> bool try_acquire_for( const std::chrono::duration<Rep, Period>& rel_time ); ``` | | (since C++20) | Tries to atomically decrement the internal counter by `1` if it is greater than `​0​`; otherwise blocks until it is greater than `​0​` and can successfully decrement the internal counter, or the `rel_time` duration has been exceeded. ### Preconditions (none). ### Parameters | | | | | --- | --- | --- | | rel\_time | - | the *minimum* duration the function must wait for to fail | ### Return value `true` if it decremented the internal counter, otherwise `false`. ### Exceptions May throw `[std::system\_error](../../error/system_error "cpp/error/system error")` or a timeout-related exception. ### Notes In practice the function may take longer than `rel_time` to fail. cpp std::counting_semaphore<LeastMaxValue>::release std::counting\_semaphore<LeastMaxValue>::release ================================================ | | | | | --- | --- | --- | | ``` void release( std::ptrdiff_t update = 1 ); ``` | | (since C++20) | Atomically increments the internal counter by the value of `update`. Any thread(s) waiting for the counter to be greater than `​0​`, such as due to being blocked in `acquire`, will subsequently be unblocked. ### Preconditions Both `update >= 0` and `update <= max() - counter` are `true`, where `counter` is the value of the internal counter. ### Parameters | | | | | --- | --- | --- | | update | - | the amount to increment the internal counter by | ### Exceptions May throw `[std::system\_error](../../error/system_error "cpp/error/system error")`. cpp std::counting_semaphore<LeastMaxValue>::max std::counting\_semaphore<LeastMaxValue>::max ============================================ | | | | | --- | --- | --- | | ``` constexpr std::ptrdiff_t max() noexcept; ``` | | (since C++20) | Returns the internal counter's maximum possible value, which is greater than or equal to `LeastMaxValue`. ### Return value The internal counter's maximum possible value, as a `[std::ptrdiff\_t](../../types/ptrdiff_t "cpp/types/ptrdiff t")`. ### Notes For specialization `binary_semaphore`, `LeastMaxValue` is equal to `1`. As its name indicates, the `LeastMaxValue` is the *minimum* max value, not the *actual* max value. Thus `max()` can yield a number larger than `LeastMaxValue`. cpp std::counting_semaphore<LeastMaxValue>::counting_semaphore std::counting\_semaphore<LeastMaxValue>::counting\_semaphore ============================================================ | | | | | --- | --- | --- | | ``` constexpr explicit counting_semaphore( std::ptrdiff_t desired ); ``` | (1) | (since C++20) | | ``` counting_semaphore( const counting_semaphore& ) = delete; ``` | (2) | (since C++20) | 1) Constructs an object of type `std::counting_semaphore` with the internal counter initialized to `desired`. 2) Copy constructor is deleted. ### Preconditions 1) Both `desired >= 0` and `desired <= max()` are `true`. ### Parameters | | | | | --- | --- | --- | | desired | - | the value to initialize `counting_semaphore`'s counter with | ### Exceptions Throws nothing. cpp std::counting_semaphore<LeastMaxValue>::try_acquire std::counting\_semaphore<LeastMaxValue>::try\_acquire ===================================================== | | | | | --- | --- | --- | | ``` bool try_acquire() noexcept; ``` | | (since C++20) | Tries to atomically decrement the internal counter by `1` if it is greater than `​0​`; no blocking occurs regardless. ### Return value `true` if it decremented the internal counter, otherwise `false`. ### Notes Implementations are allowed to fail to decrement the counter even if it was greater than `​0​` - i.e., they are allowed to spuriously fail and return `false`. cpp std::counting_semaphore<LeastMaxValue>::~counting_semaphore std::counting\_semaphore<LeastMaxValue>::~counting\_semaphore ============================================================= | | | | | --- | --- | --- | | ``` ~counting_semaphore(); ``` | | (since C++20) | Destroys the `counting_semaphore` object. The behavior is undefined if any thread is concurrently calling any other member function on this semaphore. This includes threads blocked in `acquire()`, `try_acquire_for()`, or `try_acquire_until()`. cpp std::counting_semaphore<LeastMaxValue>::try_acquire_until std::counting\_semaphore<LeastMaxValue>::try\_acquire\_until ============================================================ | | | | | --- | --- | --- | | ``` template<class Clock, class Duration> bool try_acquire_until( const std::chrono::time_point<Clock, Duration>& abs_time ); ``` | | (since C++20) | Tries to atomically decrement the internal counter by `1` if it is greater than `​0​`; otherwise blocks until it is greater than `​0​` and can successfully decrement the internal counter, or the `abs_time` time point has been passed. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. ### Preconditions `Clock` meets the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. ### Parameters | | | | | --- | --- | --- | | abs\_time | - | the *earliest* time the function must wait until in order to fail | ### Return value `true` if it decremented the internal counter, otherwise `false`. ### Exceptions May throw `[std::system\_error](../../error/system_error "cpp/error/system error")` or a timeout-related exception. ### Notes In practice the function may take longer than `abs_time` to fail. cpp std::thread::join std::thread::join ================= | | | | | --- | --- | --- | | ``` void join(); ``` | | (since C++11) | Blocks the current thread until the thread identified by `*this` finishes its execution. The completion of the thread identified by `*this` *synchronizes with* the corresponding successful return from `join()`. No synchronization is performed on `*this` itself. Concurrently calling `join()` on the same thread object from multiple threads constitutes a data race that results in undefined behavior. ### Parameters (none). ### Return value (none). ### Postconditions `[joinable()](joinable "cpp/thread/thread/joinable")` is `false`. ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if an error occurs. ### Error Conditions * `[resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` if `this->get_id() == [std::this\_thread::get\_id](http://en.cppreference.com/w/cpp/thread/get_id)()` (deadlock detected) * `[no\_such\_process](../../error/errc "cpp/error/errc")` if the thread is not valid * `[invalid\_argument](../../error/errc "cpp/error/errc")` if `[joinable()](joinable "cpp/thread/thread/joinable")` is `false` ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { // simulate expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { // simulate expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::cout << "starting first helper...\n"; std::thread helper1(foo); std::cout << "starting second helper...\n"; std::thread helper2(bar); std::cout << "waiting for helpers to finish..." << std::endl; helper1.join(); helper2.join(); std::cout << "done!\n"; } ``` Output: ``` starting first helper... starting second helper... waiting for helpers to finish... done! ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.2.5 Members [thread.thread.member] * C++17 standard (ISO/IEC 14882:2017): + 33.3.2.5 thread members [thread.thread.member] * C++14 standard (ISO/IEC 14882:2014): + 30.3.1.5 thread members [thread.thread.member] * C++11 standard (ISO/IEC 14882:2011): + 30.3.1.5 thread members [thread.thread.member] ### See also | | | | --- | --- | | [detach](detach "cpp/thread/thread/detach") | permits the thread to execute independently from the thread handle (public member function) | | [joinable](joinable "cpp/thread/thread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_join "c/thread/thrd join") for `thrd_join` |
programming_docs
cpp std::thread::~thread std::thread::~thread ==================== | | | | | --- | --- | --- | | ``` ~thread(); ``` | | (since C++11) | Destroys the thread object. If `*this` has an associated thread (`joinable() == true`), `[std::terminate](http://en.cppreference.com/w/cpp/error/terminate)()` is called. ### Notes A thread object does not have an associated thread (and is safe to destroy) after. * it was default-constructed * it was moved from * `[join()](join "cpp/thread/thread/join")` has been called * `[detach()](detach "cpp/thread/thread/detach")` has been called cpp std::thread::id std::thread::id =============== | Defined in header `[<thread>](../../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` class thread::id; ``` | | (since C++11) | The class `thread::id` is a lightweight, trivially copyable class that serves as a unique identifier of `[std::thread](../thread "cpp/thread/thread")` and `[std::jthread](../jthread "cpp/thread/jthread")` (since C++20) objects. Instances of this class may also hold the special distinct value that does not represent any thread. Once a thread has finished, the value of `std::thread::id` may be reused by another thread. This class is designed for use as key in associative containers, both ordered and unordered. ### Member functions | | | | --- | --- | | [(constructor)](id/id "cpp/thread/thread/id/id") | constructs an id that does not represent a thread (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator< operator<= operator> operator>= operator<=>](id/operator_cmp "cpp/thread/thread/id/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares two `thread::id` objects (function) | | [operator<<](id/operator_ltlt "cpp/thread/thread/id/operator ltlt") | serializes a `thread::id` object (function template) | ### Helper classes | | | | --- | --- | | [std::hash<std::thread::id>](id/hash "cpp/thread/thread/id/hash") | specializes `[std::hash](../../utility/hash "cpp/utility/hash")` (class template specialization) | ### See also | | | | --- | --- | | [get\_id](get_id "cpp/thread/thread/get id") | returns the *id* of the thread (public member function) | | [get\_id](../get_id "cpp/thread/get id") (C++11) | returns the thread id of the current thread (function) | cpp std::thread::swap std::thread::swap ================= | | | | | --- | --- | --- | | ``` void swap( std::thread& other ) noexcept; ``` | | (since C++11) | Exchanges the underlying handles of two thread objects. ### Parameters | | | | | --- | --- | --- | | other | - | the thread to swap with | ### Return value (none). ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::thread t1(foo); std::thread t2(bar); std::cout << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; std::swap(t1, t2); std::cout << "after std::swap(t1, t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.swap(t2); std::cout << "after t1.swap(t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.join(); t2.join(); } ``` Possible output: ``` thread 1 id: 140185268262656 thread 2 id: 140185259869952 after std::swap(t1, t2): thread 1 id: 140185259869952 thread 2 id: 140185268262656 after t1.swap(t2): thread 1 id: 140185268262656 thread 2 id: 140185259869952 ``` ### See also | | | | --- | --- | | [std::swap(std::thread)](swap2 "cpp/thread/thread/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | cpp std::thread::detach std::thread::detach =================== | | | | | --- | --- | --- | | ``` void detach(); ``` | | (since C++11) | Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. After calling `detach` `*this` no longer owns any thread. ### Parameters (none). ### Return value (none). ### Postconditions `[joinable](joinable "cpp/thread/thread/joinable")` is `false`. ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if `joinable() == false` or an error occurs. ### Example ``` #include <iostream> #include <chrono> #include <thread> void independentThread() { std::cout << "Starting concurrent thread.\n"; std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "Exiting concurrent thread.\n"; } void threadCaller() { std::cout << "Starting thread caller.\n"; std::thread t(independentThread); t.detach(); std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "Exiting thread caller.\n"; } int main() { threadCaller(); std::this_thread::sleep_for(std::chrono::seconds(5)); } ``` Possible output: ``` Starting thread caller. Starting concurrent thread. Exiting thread caller. Exiting concurrent thread. ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.2.5 Members [thread.thread.member] * C++17 standard (ISO/IEC 14882:2017): + 33.3.2.5 thread members [thread.thread.member] * C++14 standard (ISO/IEC 14882:2014): + 30.3.1.5 thread members [thread.thread.member] * C++11 standard (ISO/IEC 14882:2011): + 30.3.1.5 thread members [thread.thread.member] ### See also | | | | --- | --- | | [join](join "cpp/thread/thread/join") | waits for the thread to finish its execution (public member function) | | [joinable](joinable "cpp/thread/thread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_detach "c/thread/thrd detach") for `thrd_detach` | cpp std::swap(std::thread) std::swap(std::thread) ====================== | | | | | --- | --- | --- | | ``` void swap( std::thread &lhs, std::thread &rhs ) noexcept; ``` | | (since C++11) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::thread](../thread "cpp/thread/thread")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | threads whose states to swap | ### Return value (none). ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { using std::swap; std::thread t1(foo); std::thread t2(bar); std::cout << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; swap(t1, t2); std::cout << "after std::swap(t1, t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.swap(t2); std::cout << "after t1.swap(t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.join(); t2.join(); } ``` Possible output: ``` thread 1 id: 1892 thread 2 id: 2584 after std::swap(t1, t2): thread 1 id: 2584 thread 2 id: 1892 after t1.swap(t2): thread 1 id: 1892 thread 2 id: 2584 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/thread/thread/swap") | swaps two thread objects (public member function) | cpp std::thread::hardware_concurrency std::thread::hardware\_concurrency ================================== | | | | | --- | --- | --- | | ``` static unsigned int hardware_concurrency() noexcept; ``` | | (since C++11) | Returns the number of concurrent threads supported by the implementation. The value should be considered only a hint. ### Parameters (none). ### Return value Number of concurrent threads supported. If the value is not well defined or not computable, returns `​0​`. ### Example ``` #include <iostream> #include <thread> int main() { unsigned int n = std::thread::hardware_concurrency(); std::cout << n << " concurrent threads are supported.\n"; } ``` Possible output: ``` 4 concurrent threads are supported. ``` ### See also | | | | --- | --- | | [hardware\_destructive\_interference\_sizehardware\_constructive\_interference\_size](../hardware_destructive_interference_size "cpp/thread/hardware destructive interference size") (C++17) | min offset to avoid false sharingmax offset to promote true sharing (constant) | cpp std::thread::get_id std::thread::get\_id ==================== | | | | | --- | --- | --- | | ``` std::thread::id get_id() const noexcept; ``` | | (since C++11) | Returns a value of `[std::thread::id](id "cpp/thread/thread/id")` identifying the thread associated with `*this`. ### Parameters (none). ### Return value A value of type `[std::thread::id](id "cpp/thread/thread/id")` identifying the thread associated with `*this`. If there is no thread associated, default constructed `[std::thread::id](id "cpp/thread/thread/id")` is returned. ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::thread t1(foo); std::thread::id t1_id = t1.get_id(); std::thread t2(foo); std::thread::id t2_id = t2.get_id(); std::cout << "t1's id: " << t1_id << '\n'; std::cout << "t2's id: " << t2_id << '\n'; t1.join(); t2.join(); } ``` Possible output: ``` t1's id: 0x35a7210f t2's id: 0x35a311c4 ``` ### See also | | | | --- | --- | | [id](id "cpp/thread/thread/id") | represents the *id* of a thread (public member class) | | [joinable](joinable "cpp/thread/thread/joinable") | checks whether the thread is joinable, i.e. potentially running in parallel context (public member function) | cpp std::thread::operator= std::thread::operator= ====================== | | | | | --- | --- | --- | | ``` thread& operator=( thread&& other ) noexcept; ``` | | (since C++11) | If `*this` still has an associated running thread (i.e. `joinable() == true`), calls `[std::terminate](http://en.cppreference.com/w/cpp/error/terminate)()`. Otherwise, assigns the state of `other` to `*this` and sets `other` to a default constructed state. After this call, `this->get_id()` is equal to the value of `other.get_id()` prior to the call, and `other` no longer represents a thread of execution. ### Parameters | | | | | --- | --- | --- | | other | - | another thread object to assign to this thread object | ### Return value `*this`. cpp std::thread::joinable std::thread::joinable ===================== | | | | | --- | --- | --- | | ``` bool joinable() const noexcept; ``` | | (since C++11) | Checks if the `std::thread` object identifies an active thread of execution. Specifically, returns `true` if `get_id() != [std::thread::id](http://en.cppreference.com/w/cpp/thread/thread/id)()`. So a default constructed thread is not joinable. A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable. ### Parameters (none). ### Return value `true` if the thread object identifies an active thread of execution, `false` otherwise. ### Example ``` #include <iostream> #include <thread> #include <chrono> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { std::thread t; std::cout << "before starting, joinable: " << std::boolalpha << t.joinable() << '\n'; t = std::thread(foo); std::cout << "after starting, joinable: " << t.joinable() << '\n'; t.join(); std::cout << "after joining, joinable: " << t.joinable() << '\n'; } ``` Output: ``` before starting, joinable: false after starting, joinable: true after joining, joinable: false ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.2.5 Members [thread.thread.member] * C++17 standard (ISO/IEC 14882:2017): + 33.3.2.5 thread members [thread.thread.member] * C++14 standard (ISO/IEC 14882:2014): + 30.3.1.5 thread members [thread.thread.member] * C++11 standard (ISO/IEC 14882:2011): + 30.3.1.5 thread members [thread.thread.member] ### See also | | | | --- | --- | | [get\_id](get_id "cpp/thread/thread/get id") | returns the *id* of the thread (public member function) | | [join](join "cpp/thread/thread/join") | waits for the thread to finish its execution (public member function) | | [detach](detach "cpp/thread/thread/detach") | permits the thread to execute independently from the thread handle (public member function) | cpp std::thread::native_handle std::thread::native\_handle =========================== | | | | | --- | --- | --- | | ``` native_handle_type native_handle(); ``` | | (since C++11) (not always present) | Returns the implementation defined underlying thread handle. ### Parameters (none). ### Return value implementation defined handle type representing the thread. ### Exceptions May throw implementation-defined exceptions. ### Example Uses `native_handle` to enable realtime scheduling of C++ threads on a POSIX system. ``` #include <thread> #include <mutex> #include <iostream> #include <chrono> #include <cstring> #include <pthread.h> std::mutex iomutex; void f(int num) { std::this_thread::sleep_for(std::chrono::seconds(1)); sched_param sch; int policy; pthread_getschedparam(pthread_self(), &policy, &sch); std::lock_guard<std::mutex> lk(iomutex); std::cout << "Thread " << num << " is executing at priority " << sch.sched_priority << '\n'; } int main() { std::thread t1(f, 1), t2(f, 2); sched_param sch; int policy; pthread_getschedparam(t1.native_handle(), &policy, &sch); sch.sched_priority = 20; if (pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch)) { std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n'; } t1.join(); t2.join(); } ``` Output: ``` Thread 2 is executing at priority 0 Thread 1 is executing at priority 20 ``` cpp std::thread::thread std::thread::thread =================== | | | | | --- | --- | --- | | ``` thread() noexcept; ``` | (1) | (since C++11) | | ``` thread( thread&& other ) noexcept; ``` | (2) | (since C++11) | | ``` template< class Function, class... Args > explicit thread( Function&& f, Args&&... args ); ``` | (3) | (since C++11) | | ``` thread( const thread& ) = delete; ``` | (4) | (since C++11) | Constructs new thread object. 1) Creates new thread object which does not represent a thread. 2) Move constructor. Constructs the thread object to represent the thread of execution that was represented by `other`. After this call `other` no longer represents a thread of execution. 3) Creates new `std::thread` object and associates it with a thread of execution. The new thread of execution starts executing `/*INVOKE*/(std::move(f_copy), std::move(args_copy)...)`, where * `/*INVOKE*/` performs the `*INVOKE*` operation specified in [Callable](../../named_req/callable "cpp/named req/Callable"), which can be performed by `[std::invoke](../../utility/functional/invoke "cpp/utility/functional/invoke")` (since C++17), and * `f_copy` is an object of type `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Function>::type` and constructed from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Function>(f)`, and * `args_copy...` are objects of types `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Args>::type...` and constructed from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. Constructions of these objects are executed in the context of the caller, so that any exceptions thrown during evaluation and copying/moving of the arguments are thrown in the current thread, without starting the new thread. The program is ill-formed if any construction or the `*INVOKE*` operation is invalid. This constructor does not participate in overload resolution if `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<Function>::type` is the same type as `thread`. The completion of the invocation of the constructor *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) the beginning of the invocation of the copy of *f* on the new thread of execution. 4) The copy constructor is deleted; threads are not copyable. No two `std::thread` objects may represent the same thread of execution. ### Parameters | | | | | --- | --- | --- | | other | - | another thread object to construct this thread object with | | f | - | [Callable](../../named_req/callable "cpp/named req/Callable") object to execute in the new thread | | args... | - | arguments to pass to the new function | ### Postconditions 1) `[get\_id()](get_id "cpp/thread/thread/get id")` equal to `[std::thread::id()](id "cpp/thread/thread/id")` (i.e. `[joinable](joinable "cpp/thread/thread/joinable")` is `false`) 2) `other.get_id()` equal to `[std::thread::id()](id "cpp/thread/thread/id")` and `[get\_id()](get_id "cpp/thread/thread/get id")` returns the value of `other.get_id()` prior to the start of construction 3) `[get\_id()](get_id "cpp/thread/thread/get id")` not equal to `[std::thread::id()](id "cpp/thread/thread/id")` (i.e. `[joinable](joinable "cpp/thread/thread/joinable")` is `true`) ### Exceptions 3) `[std::system\_error](../../error/system_error "cpp/error/system error")` if the thread could not be started. The exception may represent the error condition `std::errc::resource_unavailable_try_again` or another implementation-specific error condition. ### Notes The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with `[std::ref](../../utility/functional/ref "cpp/utility/functional/ref")` or `[std::cref](../../utility/functional/ref "cpp/utility/functional/ref")`). Any return value from the function is ignored. If the function throws an exception, `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. In order to pass return values or exceptions back to the calling thread, `[std::promise](../promise "cpp/thread/promise")` or `[std::async](../async "cpp/thread/async")` may be used. ### Example ``` #include <iostream> #include <utility> #include <thread> #include <chrono> void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 1 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } class foo { public: void bar() { for (int i = 0; i < 5; ++i) { std::cout << "Thread 3 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int n = 0; }; class baz { public: void operator()() { for (int i = 0; i < 5; ++i) { std::cout << "Thread 4 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int n = 0; }; int main() { int n = 0; foo f; baz b; std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f std::thread t6(b); // t6 runs baz::operator() on a copy of object b t2.join(); t4.join(); t5.join(); t6.join(); std::cout << "Final value of n is " << n << '\n'; std::cout << "Final value of f.n (foo::n) is " << f.n << '\n'; std::cout << "Final value of b.n (baz::n) is " << b.n << '\n'; } ``` Possible output: ``` Thread 1 executing Thread 2 executing Thread 3 executing Thread 4 executing Thread 3 executing Thread 1 executing Thread 2 executing Thread 4 executing Thread 2 executing Thread 3 executing Thread 1 executing Thread 4 executing Thread 3 executing Thread 2 executing Thread 1 executing Thread 4 executing Thread 3 executing Thread 1 executing Thread 2 executing Thread 4 executing Final value of n is 5 Final value of f.n (foo::n) is 5 Final value of b.n (baz::n) is 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 2097](https://cplusplus.github.io/LWG/issue2097) | C++11 | constructor taking a Callable object might be ambiguous with the move constructor | constrained | ### References * C++20 standard (ISO/IEC 14882:2020): + 32.4.2.2 thread constructors [thread.thread.constr] * C++17 standard (ISO/IEC 14882:2017): + 33.3.2.2 thread constructors [thread.thread.constr] * C++14 standard (ISO/IEC 14882:2014): + 30.3.1.2 thread constructors [thread.thread.constr] * C++11 standard (ISO/IEC 14882:2011): + 30.3.1.2 thread constructors [thread.thread.constr] ### See also | | | | --- | --- | | [(constructor)](../jthread/jthread "cpp/thread/jthread/jthread") | constructs new jthread object (public member function of `std::jthread`) | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_create "c/thread/thrd create") for `thrd_create` |
programming_docs
cpp operator<<(std::thread::id) operator<<(std::thread::id) =========================== | Defined in header `[<thread>](../../../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT,Traits>& operator<<( std::basic_ostream<CharT,Traits>& ost, std::thread::id id ); ``` | | (since C++11) | Writes a textual representation of a thread identifier `id` to the output stream `ost`. If two thread identifiers compare equal, they have identical textual representations; if they do not compare equal, their representations are distinct. ### Parameters | | | | | --- | --- | --- | | ost | - | output stream to insert the data into | | id | - | thread identifier | ### Return value `ost`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <chrono> #include <thread> using namespace std::chrono; int main() { std::thread t1([]{ std::this_thread::sleep_for(256ms); }); std::thread t2([]{ std::this_thread::sleep_for(512ms); }); std::clog << t1.get_id() << '\n' << t2.get_id() << '\n'; t1.join(); t2.join(); } ``` Possible output: ``` 141592653589793 141421356237309 ``` cpp std::thread::id::id std::thread::id::id =================== | | | | | --- | --- | --- | | ``` id() noexcept; ``` | | (since C++11) | Default-constructs a new thread identifier. The identifier does not represent a thread. ### Parameters (none). cpp operator==,!=,<,<=,>,>=,<=>(std::thread::id) operator==,!=,<,<=,>,>=,<=>(std::thread::id) ============================================ | Defined in header `[<thread>](../../../header/thread "cpp/header/thread")` | | | | --- | --- | --- | | ``` bool operator==( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (1) | (since C++11) | | ``` bool operator!=( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (2) | (since C++11) (until C++20) | | ``` bool operator< ( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (3) | (since C++11) (until C++20) | | ``` bool operator<=( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (4) | (since C++11) (until C++20) | | ``` bool operator> ( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (5) | (since C++11) (until C++20) | | ``` bool operator>=( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (6) | (since C++11) (until C++20) | | ``` std::strong_ordering operator<=>( std::thread::id lhs, std::thread::id rhs ) noexcept; ``` | (7) | (since C++20) | Compares two thread identifiers. 1-2) Checks whether `lhs` and `rhs` represent either the same thread, or no thread. 3-7) Compares `lhs` and `rhs` in an unspecified total ordering. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | thread identifiers to compare | ### Return value 1-6) `true` if the corresponding relation holds, `false` otherwise. 7) `std::strong_ordering::less` if `lhs` is less than `rhs` in the total ordering; otherwise `std::strong_ordering::greater` if `rhs` is less than `lhs` in the total ordering; otherwise `std::strong_ordering::equal`. ### Complexity Constant. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/thrd_equal "c/thread/thrd equal") for `thrd_equal` | cpp std::future<T>::future std::future<T>::future ====================== | | | | | --- | --- | --- | | ``` future() noexcept; ``` | (1) | (since C++11) | | ``` future( future&& other ) noexcept; ``` | (2) | (since C++11) | | ``` future( const future& other ) = delete; ``` | (3) | (since C++11) | Constructs a `std::future` object. 1) Default constructor. Constructs a `std::future` with no shared state. After construction, [`valid()`](valid "cpp/thread/future/valid") `== false`. 2) Move constructor. Constructs a `std::future` with the shared state of `other` using move semantics. After construction, `other.valid() == false`. 3) `std::future` is not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). ### Parameters | | | | | --- | --- | --- | | other | - | another `std::future` to acquire shared state from | cpp std::future<T>::wait_for std::future<T>::wait\_for ========================= | | | | | --- | --- | --- | | ``` template< class Rep, class Period > std::future_status wait_for( const std::chrono::duration<Rep,Period>& timeout_duration ) const; ``` | | (since C++11) | Waits for the result to become available. Blocks until specified `timeout_duration` has elapsed or the result becomes available, whichever comes first. The return value identifies the state of the result. If the future is the result of a call to `[std::async](../async "cpp/thread/async")` that used lazy evaluation, this function returns immediately without waiting. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments. The behavior is undefined if [`valid()`](valid "cpp/thread/future/valid") is `false` before the call to this function. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | maximum duration to block for | ### Return value | Constant | Explanation | | --- | --- | | [`future_status::deferred`](../future_status "cpp/thread/future status") | The shared state contains a deferred function using lazy evaluation, so the result will be computed only when explicitly requested | | [`future_status::ready`](../future_status "cpp/thread/future status") | The result is ready | | [`future_status::timeout`](../future_status "cpp/thread/future status") | The timeout has expired | ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Notes The implementations are encouraged to detect the case when `valid == false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of `[std::future\_errc::no\_state](../future_errc "cpp/thread/future errc")`. ### Example ``` #include <iostream> #include <future> #include <thread> #include <chrono> using namespace std::chrono_literals; int main() { std::future<int> future = std::async(std::launch::async, [](){ std::this_thread::sleep_for(3s); return 8; }); std::cout << "waiting...\n"; std::future_status status; do { switch(status = future.wait_for(1s); status) { case std::future_status::deferred: std::cout << "deferred\n"; break; case std::future_status::timeout: std::cout << "timeout\n"; break; case std::future_status::ready: std::cout << "ready!\n"; break; } } while (status != std::future_status::ready); std::cout << "result is " << future.get() << '\n'; } ``` Possible output: ``` waiting... timeout timeout timeout ready! result is 8 ``` ### See also | | | | --- | --- | | [wait](wait "cpp/thread/future/wait") | waits for the result to become available (public member function) | | [wait\_until](wait_until "cpp/thread/future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function) | cpp std::future<T>::valid std::future<T>::valid ===================== | | | | | --- | --- | --- | | ``` bool valid() const noexcept; ``` | | (since C++11) | Checks if the future refers to a shared state. This is the case only for futures that were not default-constructed or moved from (i.e. returned by `[std::promise::get\_future()](../promise/get_future "cpp/thread/promise/get future")`, `[std::packaged\_task::get\_future()](../packaged_task/get_future "cpp/thread/packaged task/get future")` or `[std::async()](../async "cpp/thread/async")`) until the first time `[get()](get "cpp/thread/future/get")` or `[share()](share "cpp/thread/future/share")` is called. The behavior is undefined if any member function other than the destructor, the move-assignment operator, or `valid` is called on a `future` that does not refer to shared state (although implementations are encouraged to throw `[std::future\_error](../future_error "cpp/thread/future error")` indicating `no_state` in this case). It is valid to move from a future object for which `valid()` is `false`. ### Parameters (none). ### Return value `true` if \*this refers to a shared state, otherwise `false`. ### Example ``` #include <future> #include <iostream> int main() { std::promise<void> p; std::future<void> f = p.get_future(); std::cout << std::boolalpha; std::cout << f.valid() << '\n'; p.set_value(); std::cout << f.valid() << '\n'; f.get(); std::cout << f.valid() << '\n'; } ``` Output: ``` true true false ``` ### See also | | | | --- | --- | | [wait](wait "cpp/thread/future/wait") | waits for the result to become available (public member function) | cpp std::future<T>::operator= std::future<T>::operator= ========================= | | | | | --- | --- | --- | | ``` future& operator=( future&& other ) noexcept; ``` | (1) | (since C++11) | | ``` future& operator=( const future& other ) = delete; ``` | (2) | (since C++11) | Assigns the contents of another future object. 1) Releases any shared state and move-assigns the contents of `other` to `*this`. After the assignment, `other.valid() == false` and [`this->valid()`](valid "cpp/thread/future/valid") will yield the same value as `other.valid()` before the assignment. 2) `[std::future](../future "cpp/thread/future")` is not [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Parameters | | | | | --- | --- | --- | | other | - | a `std::future` that will transfer state to `*this` | ### Return value `*this`. cpp std::future<T>::~future std::future<T>::~future ======================= | | | | | --- | --- | --- | | ``` ~future(); ``` | | (since C++11) | Releases any shared state. This means. * if the current object holds the last reference to its shared state, the shared state is destroyed; and * the current object gives up its reference to its shared state; and | | | | --- | --- | | * these actions will not block for the shared state to become ready, except that it may block if all of the following are true: 1. the shared state was created by a call to `[std::async](../async "cpp/thread/async")`, 2. the shared state is not yet ready, and 3. this was the last reference to the shared state. | (since C++14) | In practice, these actions will block only if the task’s launch policy is `[std::launch::async](../launch "cpp/thread/launch")` (see "Effective Modern C++" Item 36), either because that was chosen by the runtime system or because it was specified in the call to `[std::async](../async "cpp/thread/async")`. cpp std::future<T>::wait_until std::future<T>::wait\_until =========================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > std::future_status wait_until( const std::chrono::time_point<Clock,Duration>& timeout_time ) const; ``` | | (since C++11) | `wait_until` waits for a result to become available. It blocks until specified `timeout_time` has been reached or the result becomes available, whichever comes first. The return value indicates why `wait_until` returned. If the future is the result of a call to [`async`](../async "cpp/thread/async") that used lazy evaluation, this function returns immediately without waiting. The behavior is undefined if `[valid()](valid "cpp/thread/future/valid")` is `false` before the call to this function, or `Clock` does not meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. (since C++20). ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value | Constant | Explanation | | --- | --- | | [`future_status::deferred`](../future_status "cpp/thread/future status") | The shared state contains a deferred function using lazy evaluation, so the result will be computed only when explicitly requested | | [`future_status::ready`](../future_status "cpp/thread/future status") | The result is ready | | [`future_status::timeout`](../future_status "cpp/thread/future status") | The timeout has expired | ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Notes The implementations are encouraged to detect the case when `valid() == false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of [`future_errc::no_state`](../future_errc "cpp/thread/future errc"). The standard recommends that the clock tied to `timeout_time` be used to measure time; that clock is not required to be a monotonic clock. There are no guarantees regarding the behavior of this function if the clock is adjusted discontinuously, but the existing implementations convert `timeout_time` from `Clock` to `[std::chrono::system\_clock](../../chrono/system_clock "cpp/chrono/system clock")` and delegate to POSIX [`pthread_cond_timedwait`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html) so that the wait honors adjustments to the system clock, but not to the user-provided `Clock`. In any case, the function also may wait for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. ### Example ``` #include <iostream> #include <future> #include <thread> #include <chrono> int main() { std::chrono::system_clock::time_point two_seconds_passed = std::chrono::system_clock::now() + std::chrono::seconds(2); // Make a future that takes 1 second to complete std::promise<int> p1; std::future<int> f_completes = p1.get_future(); std::thread([](std::promise<int> p1) { std::this_thread::sleep_for(std::chrono::seconds(1)); p1.set_value_at_thread_exit(9); }, std::move(p1) ).detach(); // Make a future that takes 5 seconds to complete std::promise<int> p2; std::future<int> f_times_out = p2.get_future(); std::thread([](std::promise<int> p2) { std::this_thread::sleep_for(std::chrono::seconds(5)); p2.set_value_at_thread_exit(8); }, std::move(p2) ).detach(); std::cout << "Waiting for 2 seconds..." << std::endl; if(std::future_status::ready == f_completes.wait_until(two_seconds_passed)) { std::cout << "f_completes: " << f_completes.get() << "\n"; } else { std::cout << "f_completes did not complete!\n"; } if(std::future_status::ready == f_times_out.wait_until(two_seconds_passed)) { std::cout << "f_times_out: " << f_times_out.get() << "\n"; } else { std::cout << "f_times_out did not complete!\n"; } std::cout << "Done!\n"; } ``` Possible output: ``` Waiting for 2 seconds... f_completes: 9 f_times_out did not complete! Done! ``` ### See also | | | | --- | --- | | [wait](wait "cpp/thread/future/wait") | waits for the result to become available (public member function) | | [wait\_for](wait_for "cpp/thread/future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function) | cpp std::future<T>::share std::future<T>::share ===================== | | | | | --- | --- | --- | | ``` std::shared_future<T> share() noexcept; ``` | | | Transfers the shared state of `*this`, if any, to a `[std::shared\_future](../shared_future "cpp/thread/shared future")` object. Multiple `[std::shared\_future](../shared_future "cpp/thread/shared future")` objects may reference the same shared state, which is not possible with `[std::future](../future "cpp/thread/future")`. After calling `share` on a `[std::future](../future "cpp/thread/future")`, [`valid()`](valid "cpp/thread/future/valid") `== false`. ### Parameters (none). ### Return value A `[std::shared\_future](../shared_future "cpp/thread/shared future")` object containing the shared state previously held by `*this`, if any, constructed as if by `[std::shared\_future](http://en.cppreference.com/w/cpp/thread/shared_future)<T>(std::move(\*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 2556](https://cplusplus.github.io/LWG/issue2556) | C++11 | `share()` requires `valid()` to be `true` | requirement removed and made `noexcept` | ### See also | | | | --- | --- | | [shared\_future](../shared_future "cpp/thread/shared future") (C++11) | waits for a value (possibly referenced by other futures) that is set asynchronously (class template) | cpp std::future<T>::get std::future<T>::get =================== | | | | | --- | --- | --- | | ``` T get(); ``` | (1) | (member only of generic `future` template)(since C++11) | | ``` T& get(); ``` | (2) | (member only of `future<T&>` template specialization)(since C++11) | | ``` void get(); ``` | (3) | (member only of `future<void>` template specialization)(since C++11) | The `get` member function waits until the `future` has a valid result and (depending on which template is used) retrieves it. It effectively calls `[wait()](wait "cpp/thread/future/wait")` in order to wait for the result. The generic template and two template specializations each contain a single version of `get`. The three versions of `get` differ only in the return type. The behavior is undefined if `[valid()](valid "cpp/thread/future/valid")` is `false` before the call to this function. Any shared state is released. `[valid()](valid "cpp/thread/future/valid")` is `false` after a call to this member function. ### Parameters (none). ### Return value 1) The value `v` stored in the shared state, as `std::move(v)`. 2) The reference stored as value in the shared state. 3) Nothing. ### Exceptions If an exception was stored in the shared state referenced by the future (e.g. via a call to [`std::promise::set_exception()`](../promise/set_exception "cpp/thread/promise/set exception")) then that exception will be thrown. ### Notes The implementations are encouraged to detect the case when `[valid()](valid "cpp/thread/future/valid")` is `false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of `[std::future\_errc::no\_state](../future_errc "cpp/thread/future errc")`. ### Example ``` #include <thread> #include <future> #include <iostream> #include <string> #include <chrono> std::string time() { static auto start = std::chrono::steady_clock::now(); std::chrono::duration<double> d = std::chrono::steady_clock::now() - start; return "[" + std::to_string(d.count()) + "s]"; } int main() { using namespace std::chrono_literals; { std::cout << time() << " launching thread\n"; std::future<int> f = std::async(std::launch::async, []{ std::this_thread::sleep_for(1s); return 7; }); std::cout << time() << " waiting for the future, f.valid() == " << f.valid() << "\n"; int n = f.get(); std::cout << time() << " future.get() returned with " << n << ". f.valid() = " << f.valid() << '\n'; } { std::cout << time() << " launching thread\n"; std::future<int> f = std::async(std::launch::async, []{ std::this_thread::sleep_for(1s); return true ? throw std::runtime_error("7") : 7; }); std::cout << time() << " waiting for the future, f.valid() == " << f.valid() << "\n"; try { int n = f.get(); std::cout << time() << " future.get() returned with " << n << " f.valid() = " << f.valid() << '\n'; } catch(const std::exception& e) { std::cout << time() << " caught exception " << e.what() << ", f.valid() == " << f.valid() << "\n"; } } } ``` Possible output: ``` [0.000004s] launching thread [0.000461s] waiting for the future, f.valid() == 1 [1.001156s] future.get() returned with 7. f.valid() = 0 [1.001192s] launching thread [1.001275s] waiting for the future, f.valid() == 1 [2.002356s] caught exception 7, f.valid() == 0 ``` ### See also | | | | --- | --- | | [valid](valid "cpp/thread/future/valid") | checks if the future has a shared state (public member function) |
programming_docs
cpp std::future<T>::wait std::future<T>::wait ==================== | | | | | --- | --- | --- | | ``` void wait() const; ``` | | (since C++11) | Blocks until the result becomes available. `valid() == true` after the call. The behavior is undefined if `[valid](valid "cpp/thread/future/valid")() == false` before the call to this function. ### Parameters (none). ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Notes The implementations are encouraged to detect the case when `valid() == false` before the call and throw a `[std::future\_error](../future_error "cpp/thread/future error")` with an error condition of `[std::future\_errc::no\_state](../future_errc "cpp/thread/future errc")`. ### Example ``` #include <chrono> #include <iostream> #include <future> #include <thread> int fib(int n) { if (n < 3) return 1; else return fib(n-1) + fib(n-2); } int main() { std::future<int> f1 = std::async(std::launch::async, [](){ return fib(40); }); std::future<int> f2 = std::async(std::launch::async, [](){ return fib(43); }); std::cout << "waiting... " << std::flush; const auto start = std::chrono::system_clock::now(); f1.wait(); f2.wait(); const auto diff = std::chrono::system_clock::now() - start; std::cout << std::chrono::duration<double>(diff).count() << " seconds\n"; std::cout << "f1: " << f1.get() << '\n'; std::cout << "f2: " << f2.get() << '\n'; } ``` Possible output: ``` waiting... 1.61803 seconds f1: 102334155 f2: 433494437 ``` ### See also | | | | --- | --- | | [wait\_for](wait_for "cpp/thread/future/wait for") | waits for the result, returns if it is not available for the specified timeout duration (public member function) | | [wait\_until](wait_until "cpp/thread/future/wait until") | waits for the result, returns if it is not available until specified time point has been reached (public member function) | cpp std::shared_timed_mutex::shared_timed_mutex std::shared\_timed\_mutex::shared\_timed\_mutex =============================================== | | | | | --- | --- | --- | | ``` shared_timed_mutex(); ``` | (1) | (since C++14) | | ``` shared_timed_mutex( const shared_timed_mutex& ) = delete; ``` | (2) | (since C++14) | 1) Constructs the mutex. The mutex is in unlocked state after the call. 2) Copy constructor is deleted. ### Parameters (none). ### Exceptions `[std::system\_error](../../error/system_error "cpp/error/system error")` if the construction is unsuccessful. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_init "c/thread/mtx init") for `mtx_init` | cpp std::shared_timed_mutex::unlock std::shared\_timed\_mutex::unlock ================================= | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++14) | Unlocks the mutex. The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent lock operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")` and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/shared timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/shared timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/shared timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_unlock "c/thread/mtx unlock") for `mtx_unlock` | cpp std::shared_timed_mutex::unlock_shared std::shared\_timed\_mutex::unlock\_shared ========================================= | | | | | --- | --- | --- | | ``` void unlock_shared(); ``` | | (since C++14) | Releases the mutex from shared ownership by the calling thread. The mutex must be locked by the current thread of execution in shared mode, otherwise, the behavior is undefined. This operation *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) any subsequent `[lock()](lock "cpp/thread/shared timed mutex/lock")` operation that obtains ownership of the same mutex. ### Parameters (none). ### Return value (none). ### Exceptions Throws nothing. ### Notes `unlock_shared()` is usually not called directly: `[std::shared\_lock](../shared_lock "cpp/thread/shared lock")` is used to manage shared locking. ### Example ### See also | | | | --- | --- | | [lock\_shared](lock_shared "cpp/thread/shared timed mutex/lock shared") | locks the mutex for shared ownership, blocks if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/shared timed mutex/unlock") | unlocks the mutex (public member function) | cpp std::shared_timed_mutex::~shared_timed_mutex std::shared\_timed\_mutex::~shared\_timed\_mutex ================================================ | | | | | --- | --- | --- | | ``` ~shared_timed_mutex(); ``` | | | Destroys the mutex. The behavior is undefined if the mutex is owned by any thread or if any thread terminates while holding any ownership of the mutex. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_destroy "c/thread/mtx destroy") for `mtx_destroy` | cpp std::shared_timed_mutex::try_lock_until std::shared\_timed\_mutex::try\_lock\_until =========================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > bool try_lock_until( const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | | (since C++14) | Tries to lock the mutex. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_time` has already passed, this function behaves like `[try\_lock()](try_lock "cpp/thread/shared timed mutex/try lock")`. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false` (since C++20). The standard recommends that the clock tied to `timeout_time` be used, in which case adjustments of the clock may be taken into account. Thus, the duration of the block might, but might not, be less or more than `timeout_time - Clock::now()` at the time of the call, depending on the direction of the adjustment and whether it is honored by the implementation. The function also may block for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. As with `[try\_lock()](try_lock "cpp/thread/shared timed mutex/try lock")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point before `timeout_time`. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. If `try_lock_until` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example This example shows a 10 seconds block. ``` #include <thread> #include <iostream> #include <chrono> #include <mutex> std::shared_timed_mutex test_mutex; void f() { auto now=std::chrono::steady_clock::now(); test_mutex.try_lock_until(now + std::chrono::seconds(10)); std::cout << "hello world\n"; } int main() { std::lock_guard<std::shared_timed_mutex> l(test_mutex); std::thread t(f); t.join(); } ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/shared timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/shared timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [unlock](unlock "cpp/thread/shared timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_timedlock "c/thread/mtx timedlock") for `mtx_timedlock` | cpp std::shared_timed_mutex::try_lock_shared_until std::shared\_timed\_mutex::try\_lock\_shared\_until =================================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > bool try_lock_shared_until( const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | | (since C++14) | Tries to lock the mutex in shared mode. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_time` has already passed, this function behaves like `[try\_lock\_shared()](try_lock_shared "cpp/thread/shared timed mutex/try lock shared")`. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The programs is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false` (since C++20). The standard recommends that the clock tied to `timeout_time` be used, in which case adjustments of the clock may be taken into account. Thus, the duration of the block might, but might not, be less or more than `timeout_time - Clock::now()` at the time of the call, depending on the direction of the adjustment and whether it is honored by the implementation. The function also may block for longer than until after `timeout_time` has been reached due to scheduling or resource contention delays. As with `[try\_lock\_shared()](try_lock_shared "cpp/thread/shared timed mutex/try lock shared")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point before `timeout_time`. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. If `try_lock_shared_until` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value `true` if the shared lock ownership was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example ### See also | | | | --- | --- | | [try\_lock\_until](try_lock_until "cpp/thread/shared timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [try\_lock\_shared](try_lock_shared "cpp/thread/shared timed mutex/try lock shared") | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) | | [try\_lock\_shared\_for](try_lock_shared_for "cpp/thread/shared timed mutex/try lock shared for") | tries to lock the mutex for shared ownership, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | cpp std::shared_timed_mutex::try_lock_shared std::shared\_timed\_mutex::try\_lock\_shared ============================================ | | | | | --- | --- | --- | | ``` bool try_lock_shared(); ``` | | (since C++14) | Tries to lock the mutex in shared mode. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currenly exclusively locked by any other thread. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. The behavior is undefined if the calling thread already owns the mutex in any mode. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/shared timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock\_shared](unlock_shared "cpp/thread/shared timed mutex/unlock shared") | unlocks the mutex (shared ownership) (public member function) | cpp std::shared_timed_mutex::lock_shared std::shared\_timed\_mutex::lock\_shared ======================================= | | | | | --- | --- | --- | | ``` void lock_shared(); ``` | | (since C++14) | Acquires shared ownership of the mutex. If another thread is holding the mutex in exclusive ownership, a call to `lock_shared` will block execution until shared ownership can be acquired. If `lock_shared` is called by a thread that already owns the `mutex` in any mode (exclusive or shared), the behavior is undefined. If more than the implementation-defined maximum number of shared owners already locked the mutex in shared mode, `lock_shared` blocks execution until the number of shared owners is reduced. The maximum number of owners is guaranteed to be at least 10000. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock_shared()` is usually not called directly: `[std::shared\_lock](../shared_lock "cpp/thread/shared lock")` is used to manage shared locking. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock\_shared](try_lock_shared "cpp/thread/shared timed mutex/try lock shared") | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) | | [unlock\_shared](unlock_shared "cpp/thread/shared timed mutex/unlock shared") | unlocks the mutex (shared ownership) (public member function) | cpp std::shared_timed_mutex::try_lock std::shared\_timed\_mutex::try\_lock ==================================== | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++14) | Tries to lock the mutex. Returns immediately. On successful lock acquisition returns `true`, otherwise returns `false`. This function is allowed to fail spuriously and return `false` even if the mutex is not currently locked by any other thread. If `try_lock` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. Note that prior `[lock()](lock "cpp/thread/shared timed mutex/lock")` does not synchronize with this operation if it returns `false`. ### Parameters (none). ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Throws nothing. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/shared timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/shared timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/shared timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_trylock "c/thread/mtx trylock") for `mtx_trylock` | cpp std::shared_timed_mutex::lock std::shared\_timed\_mutex::lock =============================== | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++14) | Locks the mutex. If another thread has already locked the mutex, a call to `lock` will block execution until the lock is acquired. If `lock` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operations on the same mutex *synchronize-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation. ### Parameters (none). ### Return value (none). ### Exceptions Throws `[std::system\_error](../../error/system_error "cpp/error/system error")` when errors occur, including errors from the underlying operating system that would prevent `lock` from meeting its specifications. The mutex is not locked in the case of any exception being thrown. ### Notes `lock()` is usually not called directly: `[std::unique\_lock](../unique_lock "cpp/thread/unique lock")`, [`std::scoped_lock`](../scoped_lock "cpp/thread/scoped lock"), and `[std::lock\_guard](../lock_guard "cpp/thread/lock guard")` are used to manage exclusive locking. Shared mutexes do not support direct transition from shared to unique ownership mode: the shared lock has to be relinquished with `[unlock\_shared()](unlock_shared "cpp/thread/shared timed mutex/unlock shared")` before exclusive ownership may be obtained with `lock()`. [boost::upgrade\_mutex](http://www.boost.org/doc/libs/release/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.upgrade_mutex) may be used for this purpose. ### Example This example shows how `lock` and `unlock` can be used to protect shared data. ``` #include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); ++g_num; // note, that the mutex also syncronizes the output std::cout << "id: " << id << ", g_num: " << g_num << '\n'; g_num_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(234)); } } int main() { std::thread t1{slow_increment, 0}; std::thread t2{slow_increment, 1}; t1.join(); t2.join(); } ``` Possible output: ``` id: 0, g_num: 1 id: 1, g_num: 2 id: 1, g_num: 3 id: 0, g_num: 4 id: 0, g_num: 5 id: 1, g_num: 6 ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/shared timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [unlock](unlock "cpp/thread/shared timed mutex/unlock") | unlocks the mutex (public member function) | | [C documentation](https://en.cppreference.com/w/c/thread/mtx_lock "c/thread/mtx lock") for `mtx_lock` |
programming_docs
cpp std::shared_timed_mutex::try_lock_for std::shared\_timed\_mutex::try\_lock\_for ========================================= | | | | | --- | --- | --- | | ``` template< class Rep, class Period > bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | | (since C++14) | Tries to lock the mutex. Blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_duration` is less or equal `timeout_duration.zero()`, the function behaves like `[try\_lock()](try_lock "cpp/thread/shared timed mutex/try lock")`. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a [`steady_clock`](../../chrono/steady_clock "cpp/chrono/steady clock") is used to measure the duration. If an implementation uses a [`system_clock`](../../chrono/system_clock "cpp/chrono/system clock") instead, the wait time may also be sensitive to clock adjustments. As with `[try\_lock()](try_lock "cpp/thread/shared timed mutex/try lock")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point during `timeout_duration`. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. If `try_lock_for` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | minimum duration to block for | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example ``` #include <iostream> #include <mutex> #include <chrono> #include <thread> #include <vector> #include <sstream> using namespace std::chrono_literals; std::mutex cout_mutex; // control access to std::cout std::timed_mutex mutex; void job(int id) { std::ostringstream stream; for (int i = 0; i < 3; ++i) { if (mutex.try_lock_for(100ms)) { stream << "success "; std::this_thread::sleep_for(100ms); mutex.unlock(); } else { stream << "failed "; } std::this_thread::sleep_for(100ms); } std::lock_guard<std::mutex> lock{cout_mutex}; std::cout << "[" << id << "] " << stream.str() << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 4; ++i) { threads.emplace_back(job, i); } for (auto& i: threads) { i.join(); } } ``` Possible output: ``` [0] failed failed failed [3] failed failed success [2] failed success failed [1] success failed success ``` ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared timed mutex/lock") | locks the mutex, blocks if the mutex is not available (public member function) | | [try\_lock](try_lock "cpp/thread/shared timed mutex/try lock") | tries to lock the mutex, returns if the mutex is not available (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/shared timed mutex/try lock until") | tries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [unlock](unlock "cpp/thread/shared timed mutex/unlock") | unlocks the mutex (public member function) | cpp std::shared_timed_mutex::try_lock_shared_for std::shared\_timed\_mutex::try\_lock\_shared\_for ================================================= | | | | | --- | --- | --- | | ``` template< class Rep, class Period > bool try_lock_shared_for( const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | | (since C++14) | Tries to lock the mutex in shared mode. Blocks until specified `timeout_duration` has elapsed or the shared lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. If `timeout_duration` is less or equal `timeout_duration.zero()`, the function behaves like `[try\_lock\_shared()](try_lock_shared "cpp/thread/shared timed mutex/try lock shared")`. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments. As with `[try\_lock\_shared()](try_lock_shared "cpp/thread/shared timed mutex/try lock shared")`, this function is allowed to fail spuriously and return `false` even if the mutex was not locked by any other thread at some point during `timeout_duration`. Prior `[unlock()](unlock "cpp/thread/shared timed mutex/unlock")` operation on the same mutex *synchronizes-with* (as defined in `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")`) this operation if it returns `true`. If `try_lock_shared_for` is called by a thread that already owns the `mutex` in any mode (shared or exclusive), the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | maximum duration to block for | ### Return value `true` if the lock was acquired successfully, otherwise `false`. ### Exceptions Any exception thrown by clock, time\_point, or duration during the execution (clocks, time points, and durations provided by the standard library never throw). ### Example ### See also | | | | --- | --- | | [try\_lock\_shared](try_lock_shared "cpp/thread/shared timed mutex/try lock shared") | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) | | [try\_lock\_shared\_until](try_lock_shared_until "cpp/thread/shared timed mutex/try lock shared until") | tries to lock the mutex for shared ownership, returns if the mutex has beenunavailable until specified time point has been reached (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/shared timed mutex/try lock for") | tries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function) | cpp std::nostopstate_t std::nostopstate\_t =================== | Defined in header `[<stop\_token>](../../header/stop_token "cpp/header/stop token")` | | | | --- | --- | --- | | ``` struct nostopstate_t { explicit nostopstate_t() = default; }; ``` | | (since C++20) | Unit type intended for use as a placeholder in `[std::stop\_source](../stop_source "cpp/thread/stop source")` non-default constructor, that makes the constructed `[std::stop\_source](../stop_source "cpp/thread/stop source")` empty with no associated stop-state. cpp std::stop_source::~stop_source std::stop\_source::~stop\_source ================================ | | | | | --- | --- | --- | | ``` ~stop_source(); ``` | | (since C++20) | Destroys the `stop_source` object. If `*this` has associated stop-state, releases ownership of it. cpp std::stop_source::request_stop std::stop\_source::request\_stop ================================ | | | | | --- | --- | --- | | ``` bool request_stop() noexcept; ``` | | (since C++20) | Issues a stop request to the stop-state, if the `stop_source` object has a stop-state and it has not yet already had stop requested. The determination is made atomically, and if stop was requested, the stop-state is atomically updated to avoid race conditions, such that: * `stop_requested()` and `stop_possible()` can be concurrently invoked on other `stop_token`s and `stop_source`s of the same stop-state; * `request_stop()` can be concurrently invoked on other `stop_source` objects, and only one will actually perform the stop request. However, see the Notes section. ### Parameters (none). ### Return value `true` if the `stop_source` object has a stop-state and this invocation made a stop request, otherwise `false`. ### Postconditions `stop_possible()` is `false` or `stop_requested()` is `true`. ### Notes If the `request_stop()` does issue a stop request (i.e., returns `true`), then any `stop_callback`s registered for the same associated stop-state will be invoked synchronously, on the same thread `request_stop()` is issued on. If an invocation of a callback exits via an exception, `[std::terminate](../../error/terminate "cpp/error/terminate")` is called. If the `stop_source` object has a stop-state but a stop request has already been made, this function returns `false`. However there is no guarantee that another `stop_source` object which has just (successfully) requested stop is not still in the middle of invoking a `stop_callback` function. If the `request_stop()` does issue a stop request (i.e., returns `true`), then all condition variables of base type `[std::condition\_variable\_any](../condition_variable_any "cpp/thread/condition variable any")` registered with an interruptible wait for `stop_token`s associated with the `stop_source`'s stop-state will be notified. ### Example cpp std::stop_source::swap std::stop\_source::swap ======================= | | | | | --- | --- | --- | | ``` void swap( std::stop_source& other ) noexcept; ``` | | (since C++20) | Exchanges the stop-state of `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | `stop_source` to exchange the contents with | ### Return value (none). cpp std::stop_source::get_token std::stop\_source::get\_token ============================= | | | | | --- | --- | --- | | ``` [[nodiscard]] std::stop_token get_token() const noexcept; ``` | | (since C++20) | Returns a `stop_token` object associated with the `stop_source`'s stop-state, if the `stop_source` has stop-state; otherwise returns a default-constructed (empty) `stop_token`. ### Parameters (none). ### Return value A `stop_token` object, which will be empty if `this->stop_possible() == false`. ### Example cpp std::stop_source::stop_requested std::stop\_source::stop\_requested ================================== | | | | | --- | --- | --- | | ``` [[nodiscard]] bool stop_requested() const noexcept; ``` | | (since C++20) | Checks if the `stop_source` object has a stop-state and that state has received a stop request. ### Parameters (none). ### Return value `true` if the `stop_token` object has a stop-state and it has received a stop request, `false` otherwise. ### Example cpp swap(std::stop_source) swap(std::stop\_source) ======================= | | | | | --- | --- | --- | | ``` friend void swap( stop_source &lhs, stop_source &rhs ) noexcept; ``` | | (since C++20) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::stop\_source](../stop_source "cpp/thread/stop source")`. Exchanges the stop-state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. 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::stop_source` is an associated class of the arguments. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `stop_source`s to swap | ### Return value (none). cpp std::stop_source::operator= std::stop\_source::operator= ============================ | | | | | --- | --- | --- | | ``` std::stop_source& operator=( const std::stop_source& other ) noexcept; ``` | (1) | (since C++20) | | ``` std::stop_source& operator=( std::stop_source&& other ) noexcept; ``` | (2) | (since C++20) | Replaces the stop-state with that of `other`. 1) Copy-assigns the stop-state of `other` to that of `*this`. Equivalent to `stop_source(other).swap(*this)`. 2) Move-assigns the stop-state of `other` to that of `*this`. After the assignment, `*this` contains the previous stop-state of `other`, and `other` has no stop-state. Equivalent to `stop_source(std::move(other)).swap(*this)`. ### Parameters | | | | | --- | --- | --- | | other | - | another `stop_source` object to share the stop-state with to or acquire the stop-state from | cpp std::nostopstate std::nostopstate ================ | Defined in header `[<stop\_token>](../../header/stop_token "cpp/header/stop token")` | | | | --- | --- | --- | | ``` inline constexpr std::nostopstate_t nostopstate{}; ``` | | (since C++20) | This is a constant object instance of `[std::nostopstate\_t](../stop_source "cpp/thread/stop source")` for use in constructing an empty `[std::stop\_source](../stop_source "cpp/thread/stop source")`, as a placeholder value in the non-default constructor. cpp std::stop_source::stop_source std::stop\_source::stop\_source =============================== | | | | | --- | --- | --- | | ``` stop_source(); ``` | (1) | (since C++20) | | ``` explicit stop_source( std::nostopstate_t nss ) noexcept; ``` | (2) | (since C++20) | | ``` stop_source( const stop_source& other ) noexcept; ``` | (3) | (since C++20) | | ``` stop_source( stop_source&& other ) noexcept; ``` | (4) | (since C++20) | Constructs a new `stop_source` object. 1) Constructs a `stop_source` with new stop-state. 2) Constructs an empty `stop_source` with no associated stop-state. 3) Copy constructor. Constructs a `stop_source` whose associated stop-state is the same as that of `other`. 4) Move constructor. Constructs a `stop_source` whose associated stop-state is the same as that of `other`; `other` is left empty. ### Parameters | | | | | --- | --- | --- | | nss | - | an `std::nostopstate_t` placeholder object to construct an empty `stop_source` | | other | - | another `stop_source` object to construct this `stop_source` object with | ### Postconditions 1) `stop_possible()` is `true` and `stop_requested()` is `false` 2) `stop_possible()` and `stop_requested()` are both `false` 3) `*this` and `other` share the same associated stop-state and compare equal 4) `*this` has `other`'s previously associated stop-state, and `other.stop_possible()` is `false` ### Exceptions 1) `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory could not be allocated for the stop-state cpp std::stop_source::stop_possible std::stop\_source::stop\_possible ================================= | | | | | --- | --- | --- | | ``` [[nodiscard]] bool stop_possible() const noexcept; ``` | | (since C++20) | Checks if the `stop_source` object has a stop-state. ### Parameters (none). ### Return value `true` if the `stop_source` object has a stop-state, otherwise `false`. ### Notes If the `stop_source` object has a stop-state and a stop request has already been made, this function still returns `true`. ### Example cpp operator==(std::stop_source) operator==(std::stop\_source) ============================= | | | | | --- | --- | --- | | ``` [[nodiscard]] friend bool operator==( const stop_source& lhs, const stop_source& rhs ) noexcept; ``` | | (since C++20) | Compares two `stop_source` values. 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::stop_source` is an associated class of the arguments. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `stop_source`s to compare | ### Return value `true` if `lhs` and `rhs` have the same stop-state, or both have no stop-state, otherwise `false`. cpp std::shared_lock<Mutex>::mutex std::shared\_lock<Mutex>::mutex =============================== | | | | | --- | --- | --- | | ``` mutex_type* mutex() const noexcept; ``` | | (since C++14) | Returns a pointer to the associated mutex, or a null pointer if there is no associated mutex. ### Parameters (none). ### Return value Pointer to the associated mutex or a null pointer if there is no associated mutex. ### Example cpp std::shared_lock<Mutex>::unlock std::shared\_lock<Mutex>::unlock ================================ | | | | | --- | --- | --- | | ``` void unlock(); ``` | | (since C++14) | Unlocks the associated mutex from shared mode. Effectively calls `mutex()->unlock_shared()`. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is not locked. ### Parameters (none). ### Return value (none). ### Exceptions * Any exceptions thrown by `mutex()->unlock_shared()` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared lock/lock") | locks the associated mutex (public member function) | | [release](release "cpp/thread/shared lock/release") | disassociates the mutex without unlocking (public member function) | cpp std::shared_lock<Mutex>::~shared_lock std::shared\_lock<Mutex>::~shared\_lock ======================================= | | | | | --- | --- | --- | | ``` ~shared_lock(); ``` | | (since C++14) | Destroys the lock. If `*this` has an associated mutex ((`[mutex()](mutex "cpp/thread/shared lock/mutex")` returns a non-null pointer) and has acquired ownership of it (`owns()` returns `true`), the mutex is unlocked by calling `[unlock\_shared()](../shared_mutex/unlock_shared "cpp/thread/shared mutex/unlock shared")`. cpp std::shared_lock<Mutex>::swap std::shared\_lock<Mutex>::swap ============================== | | | | | --- | --- | --- | | ``` template< class Mutex > void swap( shared_lock<Mutex>& other ) noexcept; ``` | | (since C++14) | Exchanges the internal states of the lock objects. ### Parameters | | | | | --- | --- | --- | | other | - | the lock to swap the state with | ### Return value (none). ### Example ### See also | | | | --- | --- | | [std::swap(std::shared\_lock)](swap2 "cpp/thread/shared lock/swap2") (C++14) | specialization of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for `shared_lock` (function template) | cpp std::shared_lock<Mutex>::operator bool std::shared\_lock<Mutex>::operator bool ======================================= | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | (since C++14) | Checks whether `*this` owns a locked mutex or not. Effectively calls `[owns\_lock()](owns_lock "cpp/thread/shared lock/owns lock")`. ### Parameters (none). ### Return value `true` if `*this` has an associated mutex and has acquired shared ownership of it, `false` otherwise. ### See also | | | | --- | --- | | [owns\_lock](owns_lock "cpp/thread/shared lock/owns lock") | tests whether the lock owns its associated mutex (public member function) | cpp std::shared_lock<Mutex>::release std::shared\_lock<Mutex>::release ================================= | | | | | --- | --- | --- | | ``` mutex_type* release() noexcept; ``` | | (since C++14) | Breaks the association of the associated mutex, if any, and `*this`. No locks are unlocked. If the `*this` held ownership of the associated mutex prior to the call, the caller is now responsible to unlock the mutex. ### Parameters (none). ### Return value Pointer to the associated mutex or a null pointer if there was no associated mutex. ### Example ### See also | | | | --- | --- | | [unlock](unlock "cpp/thread/shared lock/unlock") | unlocks the associated mutex (public member function) | | [release](../unique_lock/release "cpp/thread/unique lock/release") | disassociates the associated mutex without unlocking (i.e., releasing ownership of) it (public member function of `std::unique_lock<Mutex>`) |
programming_docs
cpp std::shared_lock<Mutex>::try_lock_until std::shared\_lock<Mutex>::try\_lock\_until ========================================== | | | | | --- | --- | --- | | ``` template< class Clock, class Duration > bool try_lock_until( const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | | (since C++14) | Tries to lock the associated mutex in shared mode. Blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. May block for longer than until `timeout_time` has been reached. Effectively calls `mutex()->try_lock_shared_until(timeout_time)`. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is already locked. `Clock` must meet the [Clock](../../named_req/clock "cpp/named req/Clock") requirements. The behavior is undefined if `Mutex` does not meet the [SharedTimedLockable](../../named_req/sharedtimedlockable "cpp/named req/SharedTimedLockable") requirements. The program is ill-formed if `[std::chrono::is\_clock\_v](http://en.cppreference.com/w/cpp/chrono/is_clock)<Clock>` is `false`. (since C++20). ### Parameters | | | | | --- | --- | --- | | timeout\_time | - | maximum time point to block until | ### Return value `true` if the ownership of the mutex has been acquired successfully, `false` otherwise. ### Exceptions * Any exceptions thrown by `mutex()->try_lock_shared_for(timeout_time)`. * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")`. * If the mutex is already locked, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")`. ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared lock/lock") | locks the associated mutex (public member function) | | [try\_lock](try_lock "cpp/thread/shared lock/try lock") | tries to lock the associated mutex (public member function) | | [try\_lock\_for](try_lock_for "cpp/thread/shared lock/try lock for") | tries to lock the associated mutex, for the specified duration (public member function) | | [unlock](unlock "cpp/thread/shared lock/unlock") | unlocks the associated mutex (public member function) | | [try\_lock\_until](../unique_lock/try_lock_until "cpp/thread/unique lock/try lock until") | tries to lock (i.e., takes ownership of) the associated [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable until specified time point has been reached (public member function of `std::unique_lock<Mutex>`) | cpp std::shared_lock<Mutex>::owns_lock std::shared\_lock<Mutex>::owns\_lock ==================================== | | | | | --- | --- | --- | | ``` bool owns_lock() const noexcept; ``` | | (since C++14) | Checks whether `*this` owns a locked mutex or not. ### Parameters (none). ### Return value `true` if `*this` has an associated mutex and has acquired shared ownership of it, `false` otherwise. ### See also | | | | --- | --- | | [operator bool](operator_bool "cpp/thread/shared lock/operator bool") | tests whether the lock owns its associated mutex (public member function) | cpp std::shared_lock<Mutex>::try_lock std::shared\_lock<Mutex>::try\_lock =================================== | | | | | --- | --- | --- | | ``` bool try_lock(); ``` | | (since C++14) | Tries to lock the associated mutex in shared mode without blocking. Effectively calls `mutex()->try_lock_shared()`. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is already locked. ### Parameters (none). ### Return value `true` if the ownership of the mutex has been acquired successfully, `false` otherwise. ### Exceptions * Any exceptions thrown by `mutex()->try_lock_shared()` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the mutex is already locked, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example ### See also | | | | --- | --- | | [lock](lock "cpp/thread/shared lock/lock") | locks the associated mutex (public member function) | | [try\_lock](../unique_lock/try_lock "cpp/thread/unique lock/try lock") | tries to lock (i.e., takes ownership of) the associated mutex without blocking (public member function of `std::unique_lock<Mutex>`) | | [try\_lock\_for](try_lock_for "cpp/thread/shared lock/try lock for") | tries to lock the associated mutex, for the specified duration (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/shared lock/try lock until") | tries to lock the associated mutex, until a specified time point (public member function) | | [unlock](unlock "cpp/thread/shared lock/unlock") | unlocks the associated mutex (public member function) | cpp std::swap(std::shared_lock) std::swap(std::shared\_lock) ============================ | | | | | --- | --- | --- | | ``` template< class Mutex > void swap( shared_lock<Mutex>& lhs, shared_lock<Mutex>& rhs ) noexcept; ``` | | (since C++14) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::shared\_lock](../shared_lock "cpp/thread/shared lock")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | lock wrappers whose states to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/thread/shared lock/swap") | swaps the data members with another shared\_lock (public member function) | cpp std::shared_lock<Mutex>::operator= std::shared\_lock<Mutex>::operator= =================================== | | | | | --- | --- | --- | | ``` shared_lock& operator=( shared_lock&& other ) noexcept; ``` | | (since C++14) | Move assignment operator. Replaces the contents with those of `other` using move semantics. If, prior to this call, `*this` has an associated mutex ((`[mutex()](mutex "cpp/thread/shared lock/mutex")` returns a non-null pointer) and has acquired ownership of it (`owns()` returns `true`), the mutex is unlocked by calling `[unlock\_shared()](../shared_mutex/unlock_shared "cpp/thread/shared mutex/unlock shared")`. After this call, `other` has no associated mutex. ### Parameters | | | | | --- | --- | --- | | other | - | another `shared_lock` to replace the state with | ### Return value `*this`. cpp std::shared_lock<Mutex>::shared_lock std::shared\_lock<Mutex>::shared\_lock ====================================== | | | | | --- | --- | --- | | ``` shared_lock() noexcept; ``` | (1) | (since C++14) | | ``` shared_lock( shared_lock&& other ) noexcept; ``` | (2) | (since C++14) | | ``` explicit shared_lock( mutex_type& m ); ``` | (3) | (since C++14) | | ``` shared_lock( mutex_type& m, std::defer_lock_t t ) noexcept; ``` | (4) | (since C++14) | | ``` shared_lock( mutex_type& m, std::try_to_lock_t t ); ``` | (5) | (since C++14) | | ``` shared_lock( mutex_type& m, std::adopt_lock_t t ); ``` | (6) | (since C++14) | | ``` template< class Rep, class Period > shared_lock( mutex_type& m, const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | (7) | (since C++14) | | ``` template< class Clock, class Duration > shared_lock( mutex_type& m, const std::chrono::time_point<Clock,Duration>& timeout_time ); ``` | (8) | (since C++14) | Constructs a `shared_lock`, optionally locking the supplied mutex. 1) Constructs a `shared_lock` with no associated mutex. 2) Move constructor. Initializes the `shared_lock` with the contents of `other`. Leaves `other` with no associated mutex. 3-8) Constructs a `shared_lock` with `m` as the associated mutex. Additionally: 3) Locks the associated mutex in shared mode by calling `m.lock_shared()`. 4) Does not lock the associated mutex. 5) Tries to lock the associated mutex in shared mode without blocking by calling `m.try_lock_shared()`. 6) Assumes the calling thread already holds a shared lock (i.e., a lock acquired by `lock_shared`, `try_lock_shared`, `try_lock_shared_for`, or `try_lock_shared_until`) on `m`. The behavior is undefined if not so. 7) Tries to lock the associated mutex in shared mode by calling `m.try_lock_shared_for(timeout_duration)`, which blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. May block for longer than `timeout_duration`. The behavior is undefined if `Mutex` does not meet the [SharedTimedLockable](../../named_req/sharedtimedlockable "cpp/named req/SharedTimedLockable") requirements. 8) Tries to lock the associated mutex in shared mode by calling `m.try_lock_shared_until(timeout_time)`, which blocks until specified `timeout_time` has been reached or the lock is acquired, whichever comes first. May block for longer than until `timeout_time` has been reached. The behavior is undefined if `Mutex` does not meet the [SharedTimedLockable](../../named_req/sharedtimedlockable "cpp/named req/SharedTimedLockable") requirements. ### Parameters | | | | | --- | --- | --- | | other | - | another `shared_lock` to initialize the state with | | m | - | mutex to associate with the lock and optionally acquire ownership of | | t | - | tag parameter used to select constructors with different locking strategies | | timeout\_duration | - | maximum duration to block for | | timeout\_time | - | maximum time point to block until | ### Example ``` #include <shared_mutex> #include <syncstream> #include <iostream> #include <thread> #include <chrono> std::shared_timed_mutex m; int i = 10; void read_shared_var(int id) { // both the threads get access to the integer i std::shared_lock<std::shared_timed_mutex> slk(m); const int ii = i; // reads global i std::osyncstream(std::cout) << "#" << id << " read i as " << ii << "...\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::osyncstream(std::cout) << "#" << id << " woke up..." << std::endl; } int main() { std::thread r1 {read_shared_var, 1}; std::thread r2 {read_shared_var, 2}; r1.join(); r2.join(); } ``` Possible output: ``` #2 read i as 10... #1 read i as 10... #2 woke up... #1 woke up... ``` cpp std::shared_lock<Mutex>::lock std::shared\_lock<Mutex>::lock ============================== | | | | | --- | --- | --- | | ``` void lock(); ``` | | (since C++14) | Locks the associated mutex in shared mode. Effectively calls `mutex()->lock_shared()`. ### Parameters (none). ### Return value (none). ### Exceptions * Any exceptions thrown by `mutex()->lock_shared()` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the associated mutex is already locked by this `shared_lock` (that is, [owns\_lock](owns_lock "cpp/thread/shared lock/owns lock") returns `true`), `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example ``` #include <iostream> #include <mutex> #include <string> #include <shared_mutex> #include <thread> std::string file = "Original content."; // Simulates a file std::mutex output_mutex; // mutex that protects output operations. std::shared_mutex file_mutex; // reader/writer mutex void read_content(int id) { std::string content; { std::shared_lock lock(file_mutex, std::defer_lock); // Do not lock it first. lock.lock(); // Lock it here. content = file; } std::lock_guard lock(output_mutex); std::cout << "Contents read by reader #" << id << ": " << content << '\n'; } void write_content() { { std::lock_guard file_lock(file_mutex); file = "New content"; } std::lock_guard output_lock(output_mutex); std::cout << "New content saved.\n"; } int main() { std::cout << "Two readers reading from file.\n" << "A writer competes with them.\n"; std::thread reader1{read_content, 1}; std::thread reader2{read_content, 2}; std::thread writer{write_content}; reader1.join(); reader2.join(); writer.join(); std::cout << "The first few operations to file are done.\n"; reader1 = std::thread{read_content, 3}; reader1.join(); } ``` Possible output: ``` Two readers reading from file. A writer competes with them. Contents read by reader #1: Original content. Contents read by reader #2: Original content. New content saved. The first few operations to file are done. Contents read by reader #3: New content ``` ### See also | | | | --- | --- | | [try\_lock](try_lock "cpp/thread/shared lock/try lock") | tries to lock the associated mutex (public member function) | | [unlock](unlock "cpp/thread/shared lock/unlock") | unlocks the associated mutex (public member function) | cpp std::shared_lock<Mutex>::try_lock_for std::shared\_lock<Mutex>::try\_lock\_for ======================================== | | | | | --- | --- | --- | | ``` template< class Rep, class Period > bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration ); ``` | | (since C++14) | Tries to lock the associated mutex in shared mode. Blocks until specified `timeout_duration` has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns `true`, otherwise returns `false`. Effectively calls `mutex()->try_lock_shared_for(timeout_duration)`. This function may block for longer than `timeout_duration` due to scheduling or resource contention delays. The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments. `[std::system\_error](../../error/system_error "cpp/error/system error")` is thrown if there is no associated mutex or if the mutex is already locked. The behavior is undefined if `Mutex` does not meet the [SharedTimedLockable](../../named_req/sharedtimedlockable "cpp/named req/SharedTimedLockable") requirements. ### Parameters | | | | | --- | --- | --- | | timeout\_duration | - | maximum duration to block for | ### Return value `true` if the ownership of the mutex has been acquired successfully, `false` otherwise. ### Exceptions * Any exceptions thrown by `mutex()->try_lock_shared_for(timeout_duration)` * If there is no associated mutex, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::operation\_not\_permitted](../../error/errc "cpp/error/errc")` * If the mutex is already locked, `[std::system\_error](../../error/system_error "cpp/error/system error")` with an error code of `[std::errc::resource\_deadlock\_would\_occur](../../error/errc "cpp/error/errc")` ### Example ### See also | | | | --- | --- | | [try\_lock\_for](../unique_lock/try_lock_for "cpp/thread/unique lock/try lock for") | attempts to lock (i.e., takes ownership of) the associated [TimedLockable](../../named_req/timedlockable "cpp/named req/TimedLockable") mutex, returns if the mutex has been unavailable for the specified time duration (public member function of `std::unique_lock<Mutex>`) | | [lock](lock "cpp/thread/shared lock/lock") | locks the associated mutex (public member function) | | [try\_lock](try_lock "cpp/thread/shared lock/try lock") | tries to lock the associated mutex (public member function) | | [try\_lock\_until](try_lock_until "cpp/thread/shared lock/try lock until") | tries to lock the associated mutex, until a specified time point (public member function) | | [unlock](unlock "cpp/thread/shared lock/unlock") | unlocks the associated mutex (public member function) | cpp std::set_unexpected std::set\_unexpected ==================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` std::unexpected_handler set_unexpected( std::unexpected_handler f ) throw(); ``` | | (until C++11) | | ``` std::unexpected_handler set_unexpected( std::unexpected_handler f ) noexcept; ``` | | (since C++11) (deprecated) (removed in C++17) | Makes `f` the new global `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")` and returns the previously installed `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")`. | | | | --- | --- | | This function is thread-safe. Every call to `std::set_unexpected` *synchronizes-with* (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the subsequent calls to `std::set_unexpected` and `[std::get\_unexpected](get_unexpected "cpp/error/get unexpected")`. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | f | - | pointer to function of type `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")`, or null pointer | ### Return value The previously-installed unexpected handler, or a null pointer value if none was installed. ### See also | | | | --- | --- | | [unexpected](unexpected "cpp/error/unexpected") (removed in C++17) | function called when dynamic exception specification is violated (function) | | [get\_unexpected](get_unexpected "cpp/error/get unexpected") (C++11)(removed in C++17) | obtains the current unexpected\_handler (function) | | [unexpected\_handler](unexpected_handler "cpp/error/unexpected handler") (removed in C++17) | the type of the function called by `[std::unexpected](unexpected "cpp/error/unexpected")` (typedef) | cpp std::terminate std::terminate ============== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` void terminate(); ``` | | (until C++11) | | ``` [[noreturn]] void terminate() noexcept; ``` | | (since C++11) | `std::terminate()` is called by the C++ runtime when the program cannot continue for any of the following reasons: 1) an [exception is thrown](../language/throw "cpp/language/throw") and not caught (it is implementation-defined whether any stack unwinding is done in this case) 2) a function directly invoked by the exception handling mechanism while handling an exception that has not yet been caught exits via an exception (e.g. a destructor of some local object, or a copy constructor constructing a catch-clause parameter) 3) the constructor or the destructor of a static or thread-local (since C++11) object throws an exception 4) a function registered with `[std::atexit](../utility/program/atexit "cpp/utility/program/atexit")` or `[std::at\_quick\_exit](../utility/program/at_quick_exit "cpp/utility/program/at quick exit")` (since C++11) throws an exception | | | | --- | --- | | 5) a [dynamic exception specification](../language/except_spec "cpp/language/except spec") is violated and the default handler for `[std::unexpected](unexpected "cpp/error/unexpected")` is executed 6) a non-default handler for `[std::unexpected](unexpected "cpp/error/unexpected")` throws an exception that violates the previously violated dynamic exception specification, if the specification does not include `[std::bad\_exception](bad_exception "cpp/error/bad exception")` | (until C++17) | | | | | --- | --- | | 7) a [noexcept specification](../language/noexcept_spec "cpp/language/noexcept spec") is violated (it is implementation-defined whether any stack unwinding is done in this case) 8) `[std::nested\_exception::rethrow\_nested](nested_exception/rethrow_nested "cpp/error/nested exception/rethrow nested")` is called for an object that isn't holding a captured exception 9) an exception is thrown from the initial function of `[std::thread](../thread/thread "cpp/thread/thread")` 10) a joinable `[std::thread](../thread/thread "cpp/thread/thread")` is destroyed or assigned to 11) `[std::condition\_variable::wait](../thread/condition_variable/wait "cpp/thread/condition variable/wait")`, `[std::condition\_variable::wait\_until](../thread/condition_variable/wait_until "cpp/thread/condition variable/wait until")`, or `[std::condition\_variable::wait\_for](../thread/condition_variable/wait_for "cpp/thread/condition variable/wait for")` fails to reach its postcondition (e.g. if relocking the mutex throws) | (since C++11) | | | | | --- | --- | | 12) a function invoked by a [parallel algorithm](../algorithm "cpp/algorithm") exits via an uncaught exception and the [execution policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") specifies termination. | (since C++17) | `std::terminate()` may also be called directly from the program. In any case, `std::terminate` calls the currently installed `[std::terminate\_handler](terminate_handler "cpp/error/terminate handler")`. The default `[std::terminate\_handler](terminate_handler "cpp/error/terminate handler")` calls `[std::abort](../utility/program/abort "cpp/utility/program/abort")`. | | | | --- | --- | | If a destructor reset the terminate handler during stack unwinding and the unwinding later led to `terminate` being called, the handler that was installed at the end of the throw expression is the one that will be called. (note: it was ambiguous whether re-throwing applied the new handlers). | (until C++11) | | If a destructor reset the terminate handler during stack unwinding, it is unspecified which handler is called if the unwinding later led to `terminate` being called. | (since C++11) | ### Parameters (none). ### Return value (none). ### Notes If the handler mechanism is not wanted, e.g. because it requires atomic operations which may bloat binary size, a direct call to `[std::abort](../utility/program/abort "cpp/utility/program/abort")` is preferred when terminating the program abnormally. Some compiler intrinsics, e.g. [`__builtin_trap`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html) (gcc, clang, and icc) or [`__debugbreak`](https://docs.microsoft.com/en-us/cpp/intrinsics/debugbreak?view=msvc-160) (msvc), can be used to terminate the program as fast as possible. ### 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 2111](https://cplusplus.github.io/LWG/issue2111) | C++11 | effect of calling `set_terminate` during stack unwinding differs from C++98 and breaks some ABIs | made unspecified | ### See also | | | | --- | --- | | [terminate\_handler](terminate_handler "cpp/error/terminate handler") | the type of the function called by `std::terminate` (typedef) | | [abort](../utility/program/abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) |
programming_docs
cpp std::nested_exception std::nested\_exception ====================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` class nested_exception; ``` | | (since C++11) | `std::nested_exception` is a polymorphic mixin class which can capture and store the current exception, making it possible to nest exceptions of arbitrary types within each other. ### Member functions | | | | --- | --- | | [(constructor)](nested_exception/nested_exception "cpp/error/nested exception/nested exception") | constructs a nested\_exception (public member function) | | [(destructor)](nested_exception/~nested_exception "cpp/error/nested exception/~nested exception") [virtual] | destructs a nested exception (virtual public member function) | | [operator=](nested_exception/operator= "cpp/error/nested exception/operator=") | replaces the contents of a nested\_exception (public member function) | | [rethrow\_nested](nested_exception/rethrow_nested "cpp/error/nested exception/rethrow nested") | throws the stored exception (public member function) | | [nested\_ptr](nested_exception/nested_ptr "cpp/error/nested exception/nested ptr") | obtains a pointer to the stored exception (public member function) | ### Non-member functions | | | | --- | --- | | [throw\_with\_nested](throw_with_nested "cpp/error/throw with nested") (C++11) | throws its argument with `std::nested_exception` mixed in (function template) | | [rethrow\_if\_nested](rethrow_if_nested "cpp/error/rethrow if nested") (C++11) | throws the exception from a `std::nested_exception` (function template) | ### Example Demonstrates construction and recursion through a nested exception object. ``` #include <iostream> #include <stdexcept> #include <exception> #include <string> #include <fstream> // prints the explanatory string of an exception. If the exception is nested, // recurses to print the explanatory of the exception it holds void print_exception(const std::exception& e, int level = 0) { std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n'; try { std::rethrow_if_nested(e); } catch(const std::exception& nestedException) { print_exception(nestedException, level+1); } catch(...) {} } // sample function that catches an exception and wraps it in a nested exception void open_file(const std::string& s) { try { std::ifstream file(s); file.exceptions(std::ios_base::failbit); } catch(...) { std::throw_with_nested( std::runtime_error("Couldn't open " + s) ); } } // sample function that catches an exception and wraps it in a nested exception void run() { try { open_file("nonexistent.file"); } catch(...) { std::throw_with_nested( std::runtime_error("run() failed") ); } } // runs the sample function above and prints the caught exception int main() { try { run(); } catch(const std::exception& e) { print_exception(e); } } ``` Possible output: ``` exception: run() failed exception: Couldn't open nonexistent.file exception: basic_ios::clear ``` ### See also | | | | --- | --- | | [exception\_ptr](exception_ptr "cpp/error/exception ptr") (C++11) | shared pointer type for handling exception objects (typedef) | | [throw\_with\_nested](throw_with_nested "cpp/error/throw with nested") (C++11) | throws its argument with `std::nested_exception` mixed in (function template) | | [rethrow\_if\_nested](rethrow_if_nested "cpp/error/rethrow if nested") (C++11) | throws the exception from a `std::nested_exception` (function template) | cpp std::error_category std::error\_category ==================== | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` class error_category; ``` | | (since C++11) | `std::error_category` serves as the base class for specific error category types, such as `[std::system\_category](system_category "cpp/error/system category")`, `[std::iostream\_category](http://en.cppreference.com/w/cpp/io/iostream_category)`, etc. Each specific category class defines the `error_code` - `error_condition` mapping and holds the explanatory strings for all error\_conditions. The objects of error category classes are treated as singletons, passed by reference. ### Member functions | | | | --- | --- | | [(constructor)](error_category/error_category "cpp/error/error category/error category") | constructs an `error_category` (public member function) | | [(destructor)](error_category/~error_category "cpp/error/error category/~error category") [virtual] | destructs an `error_category` (virtual public member function) | | operator= [deleted] | not copy assignable (public member function) | | [name](error_category/name "cpp/error/error category/name") [virtual] | obtains the name of the category (virtual public member function) | | [default\_error\_condition](error_category/default_error_condition "cpp/error/error category/default error condition") [virtual] | maps `error_code` to `error_condition` (virtual public member function) | | [equivalent](error_category/equivalent "cpp/error/error category/equivalent") [virtual] | compares `error_code` and `error_condition` for equivalence (virtual public member function) | | [message](error_category/message "cpp/error/error category/message") [virtual] | obtains the explanatory string (virtual public member function) | | [operator==operator!=operator<operator<=>](error_category/operator_cmp "cpp/error/error category/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares two error categories (function) | ### Specific error categories | | | | --- | --- | | [generic\_category](generic_category "cpp/error/generic category") (C++11) | identifies the generic error category (function) | | [system\_category](system_category "cpp/error/system category") (C++11) | identifies the operating system error category (function) | | [iostream\_category](../io/iostream_category "cpp/io/iostream category") (C++11) | identifies the iostream error category (function) | | [future\_category](../thread/future_category "cpp/thread/future category") (C++11) | identifies the future error category (function) | ### See also | | | | --- | --- | | [error\_condition](error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | | [error\_code](error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | | cpp std::uncaught_exception, std::uncaught_exceptions std::uncaught\_exception, std::uncaught\_exceptions =================================================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | | (1) | | | ``` bool uncaught_exception() throw(); ``` | (until C++11) | | ``` bool uncaught_exception() noexcept; ``` | (since C++11) (deprecated in C++17) (removed in C++20) | | ``` int uncaught_exceptions() noexcept; ``` | (2) | (since C++17) | 1) Detects if the current thread has a live exception object, that is, an exception has been thrown or rethrown and not yet entered a matching catch clause, `[std::terminate](terminate "cpp/error/terminate")` or `[std::unexpected](unexpected "cpp/error/unexpected")`. In other words, `std::uncaught_exception` detects if [stack unwinding](../language/throw#Stack_unwinding "cpp/language/throw") is currently in progress. 2) Detects how many exceptions in the current thread have been thrown or rethrown and not yet entered their matching catch clauses. Sometimes it's safe to throw an exception even while `std::uncaught_exception() == true`. For example, if [stack unwinding](../language/throw#Stack_unwinding "cpp/language/throw") causes an object to be destructed, the destructor for that object could run code that throws an exception as long as the exception is caught by some catch block before escaping the destructor. ### Parameters (none). ### Return value 1) `true` if stack unwinding is currently in progress in this thread, `false` otherwise. 2) The number of uncaught exception objects in the current thread. ### Notes An example where int-returning `uncaught_exceptions` is used is the [boost.log](http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html) library: the expression `BOOST_LOG(logger) << foo();` first creates a guard object and records the number of uncaught exceptions in its constructor. The output is performed by the guard object's destructor unless `foo()` throws (in which case the number of uncaught exceptions in the destructor is greater than what the constructor observed). [`std::experimental::scope_fail`](https://en.cppreference.com/w/cpp/experimental/scope_fail "cpp/experimental/scope fail") and [`std::experimental::scope_success`](https://en.cppreference.com/w/cpp/experimental/scope_success "cpp/experimental/scope success") in LFTS v3 rely on the functionality of `uncaught_exceptions`, because their destructors need to do different things that depend on whether is called during stack unwinding. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_uncaught_exceptions`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <exception> #include <stdexcept> struct Foo { int count = std::uncaught_exceptions(); ~Foo() { std::cout << (count == std::uncaught_exceptions() ? "~Foo() called normally\n" : "~Foo() called during stack unwinding\n"); } }; int main() { Foo f; try { Foo f; std::cout << "Exception thrown\n"; throw std::runtime_error("test exception"); } catch (const std::exception& e) { std::cout << "Exception caught: " << e.what() << '\n'; } } ``` Possible output: ``` Exception thrown ~Foo() called during stack unwinding Exception caught: test exception ~Foo() called normally ``` ### 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 70](https://cplusplus.github.io/LWG/issue70) | C++98 | the exception specification of `uncaught_exception()` was missing | specified as `throw()` | ### See also | | | | --- | --- | | [terminate](terminate "cpp/error/terminate") | function called when exception handling fails (function) | | [exception\_ptr](exception_ptr "cpp/error/exception ptr") (C++11) | shared pointer type for handling exception objects (typedef) | | [current\_exception](current_exception "cpp/error/current exception") (C++11) | captures the current exception in a `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` (function) | ### External links * [GOTW issue 47: Uncaught Exceptions](http://www.gotw.ca/gotw/047.htm) * [Rationale for `std::uncaught_exceptions`](https://wg21.link/n4152) cpp std::set_terminate std::set\_terminate =================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` std::terminate_handler set_terminate( std::terminate_handler f ) throw(); ``` | | (until C++11) | | ``` std::terminate_handler set_terminate( std::terminate_handler f ) noexcept; ``` | | (since C++11) | Makes `f` the new global terminate handler function and returns the previously installed `[std::terminate\_handler](terminate_handler "cpp/error/terminate handler")`. | | | | --- | --- | | This function is thread-safe. Every call to `std::set_terminate` *synchronizes-with* (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the subsequent `std::set_terminate` and `[std::get\_terminate](get_terminate "cpp/error/get terminate")`. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | f | - | pointer to function of type `[std::terminate\_handler](terminate_handler "cpp/error/terminate handler")`, or null pointer | ### Return value The previously-installed terminate handler, or a null pointer value if none was installed. ### Example ``` #include <iostream> #include <cstdlib> #include <exception> int main() { std::set_terminate([](){ std::cout << "Unhandled exception" << std::endl; std::abort(); }); throw 1; } ``` Possible output: ``` Unhandled exception bash: line 7: 7743 Aborted (core dumped) ./a.out ``` ### See also | | | | --- | --- | | [terminate](terminate "cpp/error/terminate") | function called when exception handling fails (function) | | [get\_terminate](get_terminate "cpp/error/get terminate") (C++11) | obtains the current terminate\_handler (function) | | [terminate\_handler](terminate_handler "cpp/error/terminate handler") | the type of the function called by `[std::terminate](terminate "cpp/error/terminate")` (typedef) | cpp std::rethrow_if_nested std::rethrow\_if\_nested ======================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` template< class E > void rethrow_if_nested( const E& e ); ``` | | (since C++11) | If `E` is not a polymorphic class type, or if `[std::nested\_exception](nested_exception "cpp/error/nested exception")` is an inaccessible or ambiguous base class of `E`, there is no effect. Otherwise, performs. ``` if (auto p = dynamic_cast<const std::nested_exception*>(std::addressof(e))) p->rethrow_nested(); ``` ### Parameters | | | | | --- | --- | --- | | e | - | the exception object to rethrow | ### Return value (none). ### Notes Unlike many related functions, this function is *not* intended to be called with a `[std::exception\_ptr](http://en.cppreference.com/w/cpp/error/exception_ptr)` but rather an actual exception reference. ### Possible implementation | | | --- | | ``` namespace details { template <class E> struct can_dynamic_cast : std::integral_constant<bool, std::is_polymorphic<E>::value && (!std::is_base_of<std::nested_exception, E>::value || std::is_convertible<E*, std::nested_exception*>::value) > { }; template <class T> void rethrow_if_nested_impl(const T& e, std::true_type) { if(auto nep = dynamic_cast<const std::nested_exception*>(std::addressof(e))) nep->rethrow_nested(); } template <class T> void rethrow_if_nested_impl(const T&, std::false_type) { } } template <class T> void rethrow_if_nested(const T& t){ details::rethrow_if_nested_impl(t, details::can_dynamic_cast<T>()); } ``` | ### Example Demonstrates construction and recursion through a nested exception object. ``` #include <iostream> #include <stdexcept> #include <exception> #include <string> #include <fstream> // prints the explanatory string of an exception. If the exception is nested, // recurses to print the explanatory of the exception it holds void print_exception(const std::exception& e, int level = 0) { std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n'; try { std::rethrow_if_nested(e); } catch(const std::exception& nestedException) { print_exception(nestedException, level+1); } catch(...) {} } // sample function that catches an exception and wraps it in a nested exception void open_file(const std::string& s) { try { std::ifstream file(s); file.exceptions(std::ios_base::failbit); } catch(...) { std::throw_with_nested( std::runtime_error("Couldn't open " + s) ); } } // sample function that catches an exception and wraps it in a nested exception void run() { try { open_file("nonexistent.file"); } catch(...) { std::throw_with_nested( std::runtime_error("run() failed") ); } } // runs the sample function above and prints the caught exception int main() { try { run(); } catch(const std::exception& e) { print_exception(e); } } ``` Possible output: ``` exception: run() failed exception: Couldn't open nonexistent.file exception: basic_ios::clear ``` ### See also | | | | --- | --- | | [nested\_exception](nested_exception "cpp/error/nested exception") (C++11) | a mixin type to capture and store current exceptions (class) | | [throw\_with\_nested](throw_with_nested "cpp/error/throw with nested") (C++11) | throws its argument with `[std::nested\_exception](nested_exception "cpp/error/nested exception")` mixed in (function template) | cpp std::unexpected_handler std::unexpected\_handler ======================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` typedef void (*unexpected_handler)(); ``` | | (deprecated in C++11) (removed in C++17) | `std::unexpected_handler` is the function pointer type (pointer to function that takes no arguments and returns void), which is installed and queried by the functions `[std::set\_unexpected](set_unexpected "cpp/error/set unexpected")` and `[std::get\_unexpected](get_unexpected "cpp/error/get unexpected")` and called by `[std::unexpected](unexpected "cpp/error/unexpected")`. The C++ implementation provides a default `std::unexpected_handler` function, which calls `[std::terminate](http://en.cppreference.com/w/cpp/error/terminate)()`. If the null pointer value is installed (by means of `[std::set\_unexpected](set_unexpected "cpp/error/set unexpected")`), the implementation may restore the default handler instead. A user-defined `std::unexpected_handler` is expected to either terminate the program or throw an exception. If it throws an exception, one of the following three situations may be encountered: 1) the exception thrown by `std::unexpected_handler` satisfies the dynamic exception specification that was violated earlier. The new exception is allowed to escape the function and stack unwinding continues. 2) the exception thrown by `std::unexpected_handler` still violates the exception specification: 2a) however, the exception specification allows `[std::bad\_exception](bad_exception "cpp/error/bad exception")`: the thrown exception object is destroyed, and `[std::bad\_exception](bad_exception "cpp/error/bad exception")` is constructed by the C++ runtime and thrown instead. 2b) the exception specification does not allow `[std::bad\_exception](bad_exception "cpp/error/bad exception")`: `[std::terminate](http://en.cppreference.com/w/cpp/error/terminate)()` is called. ### See also | | | | --- | --- | | [unexpected](unexpected "cpp/error/unexpected") (removed in C++17) | function called when dynamic exception specification is violated (function) | | [set\_unexpected](set_unexpected "cpp/error/set unexpected") (removed in C++17) | changes the function to be called by `[std::unexpected](unexpected "cpp/error/unexpected")` (function) | | [get\_unexpected](get_unexpected "cpp/error/get unexpected") (C++11)(removed in C++17) | obtains the current unexpected\_handler (function) | cpp std::get_terminate std::get\_terminate =================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` std::terminate_handler get_terminate() noexcept; ``` | | (since C++11) | Returns the currently installed `[std::terminate\_handler](terminate_handler "cpp/error/terminate handler")`, which may be a null pointer. | | | | --- | --- | | This function is thread-safe. Prior call to `[std::set\_terminate](set_terminate "cpp/error/set terminate")` *synchronizes-with* (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) this function. | (since C++11) | ### Parameters (none). ### Return value The currently installed `[std::terminate\_handler](terminate_handler "cpp/error/terminate handler")`. ### See also | | | | --- | --- | | [terminate\_handler](terminate_handler "cpp/error/terminate handler") | the type of the function called by `[std::terminate](terminate "cpp/error/terminate")` (typedef) | | [set\_terminate](set_terminate "cpp/error/set terminate") | changes the function to be called by `[std::terminate](terminate "cpp/error/terminate")` (function) |
programming_docs
cpp std::unexpected std::unexpected =============== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` void unexpected(); ``` | | (until C++11) | | ``` [[noreturn]] void unexpected(); ``` | | (since C++11) (deprecated) (removed in C++17) | `std::unexpected()` is called by the C++ runtime when a [dynamic exception specification](../language/except_spec "cpp/language/except spec") is violated: an exception is thrown from a function whose exception specification forbids exceptions of this type. `std::unexpected()` may also be called directly from the program. In either case, `std::unexpected` calls the currently installed `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")`. The default `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")` calls `[std::terminate](terminate "cpp/error/terminate")`. | | | | --- | --- | | If a destructor reset the unexpected handler during stack unwinding and the unwinding later led to `unexpected` being called, the handler that was installed at the end of the throw expression is the one that will be called. (note: it was ambiguous whether re-throwing applied the new handlers). | (until C++11) | | If a destructor reset the unexpected handler during stack unwinding, it is unspecified which handler is called if the unwinding later led to `unexpected` being called. | (since C++11) | ### Parameters (none). ### Return value (none). ### Exceptions Throw any exception thrown by the currently installed `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")`. ### 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 2111](https://cplusplus.github.io/LWG/issue2111) | C++11 | effect of calling `set_unexpected` during stack unwinding differs from C++98 and breaks some ABIs | made unspecified | ### See also | | | | --- | --- | | [unexpected](../utility/expected/unexpected "cpp/utility/expected/unexpected") (C++23) | represented as an unexpected value in expected (class template) | | [unexpected\_handler](unexpected_handler "cpp/error/unexpected handler") (removed in C++17) | the type of the function called by `std::unexpected` (typedef) | cpp Error numbers Error numbers ============= Each of the macros defined in `<cerrno>` expands to integer constant expressions with type `int`, each with a positive value, matching most of the [POSIX error codes](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/errno.h.html). The following constants are defined (the implementation may define more, as long as they begin with `'E'` followed by digits or uppercase letters). | Defined in header `[<cerrno>](../header/cerrno "cpp/header/cerrno")` | | --- | | E2BIG (C++11) | Argument list too long (macro constant) | | EACCES (C++11) | Permission denied (macro constant) | | EADDRINUSE (C++11) | Address in use (macro constant) | | EADDRNOTAVAIL (C++11) | Address not available (macro constant) | | EAFNOSUPPORT (C++11) | Address family not supported (macro constant) | | EAGAIN (C++11) | Resource unavailable, try again (macro constant) | | EALREADY (C++11) | Connection already in progress (macro constant) | | EBADF (C++11) | Bad file descriptor (macro constant) | | EBADMSG (C++11) | Bad message (macro constant) | | EBUSY (C++11) | Device or resource busy (macro constant) | | ECANCELED (C++11) | Operation canceled (macro constant) | | ECHILD (C++11) | No child processes (macro constant) | | ECONNABORTED (C++11) | Connection aborted (macro constant) | | ECONNREFUSED (C++11) | Connection refused (macro constant) | | ECONNRESET (C++11) | Connection reset (macro constant) | | EDEADLK (C++11) | Resource deadlock would occur (macro constant) | | EDESTADDRREQ (C++11) | Destination address required (macro constant) | | EDOM | Mathematics argument out of domain of function (macro constant) | | EEXIST (C++11) | File exists (macro constant) | | EFAULT (C++11) | Bad address (macro constant) | | EFBIG (C++11) | File too large (macro constant) | | EHOSTUNREACH (C++11) | Host is unreachable (macro constant) | | EIDRM (C++11) | Identifier removed (macro constant) | | EILSEQ (C++11) | Illegal byte sequence (macro constant) | | EINPROGRESS (C++11) | Operation in progress (macro constant) | | EINTR (C++11) | Interrupted function (macro constant) | | EINVAL (C++11) | Invalid argument (macro constant) | | EIO (C++11) | I/O error (macro constant) | | EISCONN (C++11) | Socket is connected (macro constant) | | EISDIR (C++11) | Is a directory (macro constant) | | ELOOP (C++11) | Too many levels of symbolic links (macro constant) | | EMFILE (C++11) | File descriptor value too large (macro constant) | | EMLINK (C++11) | Too many links (macro constant) | | EMSGSIZE (C++11) | Message too large (macro constant) | | ENAMETOOLONG (C++11) | Filename too long (macro constant) | | ENETDOWN (C++11) | Network is down (macro constant) | | ENETRESET (C++11) | Connection aborted by network (macro constant) | | ENETUNREACH (C++11) | Network unreachable (macro constant) | | ENFILE (C++11) | Too many files open in system (macro constant) | | ENOBUFS (C++11) | No buffer space available (macro constant) | | ENODATA (C++11) | No message is available on the STREAM head read queue (macro constant) | | ENODEV (C++11) | No such device (macro constant) | | ENOENT (C++11) | No such file or directory (macro constant) | | ENOEXEC (C++11) | Executable file format error (macro constant) | | ENOLCK (C++11) | No locks available (macro constant) | | ENOLINK (C++11) | Link has been severed (macro constant) | | ENOMEM (C++11) | Not enough space (macro constant) | | ENOMSG (C++11) | No message of the desired type (macro constant) | | ENOPROTOOPT (C++11) | Protocol not available (macro constant) | | ENOSPC (C++11) | No space left on device (macro constant) | | ENOSR (C++11) | No STREAM resources (macro constant) | | ENOSTR (C++11) | Not a STREAM (macro constant) | | ENOSYS (C++11) | Function not supported (macro constant) | | ENOTCONN (C++11) | The socket is not connected (macro constant) | | ENOTDIR (C++11) | Not a directory (macro constant) | | ENOTEMPTY (C++11) | Directory not empty (macro constant) | | ENOTRECOVERABLE (C++11) | State not recoverable (macro constant) | | ENOTSOCK (C++11) | Not a socket (macro constant) | | ENOTSUP (C++11) | Not supported (macro constant) | | ENOTTY (C++11) | Inappropriate I/O control operation (macro constant) | | ENXIO (C++11) | No such device or address (macro constant) | | EOPNOTSUPP (C++11) | Operation not supported on socket (macro constant) | | EOVERFLOW (C++11) | Value too large to be stored in data type (macro constant) | | EOWNERDEAD (C++11) | Previous owner died (macro constant) | | EPERM (C++11) | Operation not permitted (macro constant) | | EPIPE (C++11) | Broken pipe (macro constant) | | EPROTO (C++11) | Protocol error (macro constant) | | EPROTONOSUPPORT (C++11) | Protocol not supported (macro constant) | | EPROTOTYPE (C++11) | Protocol wrong type for socket (macro constant) | | ERANGE | Result too large (macro constant) | | EROFS (C++11) | Read-only file system (macro constant) | | ESPIPE (C++11) | Invalid seek (macro constant) | | ESRCH (C++11) | No such process (macro constant) | | ETIME (C++11) | Stream ioctl() timeout (macro constant) | | ETIMEDOUT (C++11) | Connection timed out (macro constant) | | ETXTBSY (C++11) | Text file busy (macro constant) | | EWOULDBLOCK (C++11) | Operation would block (macro constant) | | EXDEV (C++11) | Cross-device link (macro constant) | All values are required to be unique except that the values of `EOPNOTSUPP` and `ENOTSUP` may be identical and the values of `EAGAIN` and `EWOULDBLOCK` may be identical. ### Example ``` #include <iostream> #include <cmath> #include <cerrno> #include <cstring> #include <clocale> int main() { double not_a_number = std::log(-1.0); std::cout << not_a_number << '\n'; if (errno == EDOM) { std::cout << "log(-1) failed: " << std::strerror(errno) << '\n'; std::setlocale(LC_MESSAGES, "de_DE.utf8"); std::cout << "Or, in German, " << std::strerror(errno) << '\n'; } } ``` Possible output: ``` nan log(-1) failed: Numerical argument out of domain Or, in German, Das numerische Argument ist ausserhalb des Definitionsbereiches ``` ### See also | | | | --- | --- | | [errc](errc "cpp/error/errc") (C++11) | the `[std::error\_condition](error_condition "cpp/error/error condition")` enumeration listing all standard [`<cerrno>`](../header/cerrno "cpp/header/cerrno") macro constants (class) | | [errno](errno "cpp/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) | | [perror](../io/c/perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [strerror](../string/byte/strerror "cpp/string/byte/strerror") | returns a text version of a given error code (function) | | [C documentation](https://en.cppreference.com/w/c/error/errno_macros "c/error/errno macros") for Error numbers | cpp std::runtime_error std::runtime\_error =================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class runtime_error; ``` | | | Defines a type of object to be thrown as exception. It reports errors that are due to events beyond the scope of the program and can not be easily predicted. Exceptions of type `std::runtime_error` are thrown by the following standard library components: `[std::locale::locale](../locale/locale/locale "cpp/locale/locale/locale")` and `[std::locale::combine](../locale/locale/combine "cpp/locale/locale/combine")`. In addition, the following standard exception types are derived from `std::runtime_error`: * `[std::range\_error](range_error "cpp/error/range error")` * `[std::overflow\_error](overflow_error "cpp/error/overflow error")` * `[std::underflow\_error](underflow_error "cpp/error/underflow error")` | | | | --- | --- | | * `[std::regex\_error](../regex/regex_error "cpp/regex/regex error")` * `[std::system\_error](system_error "cpp/error/system error")` | (since C++11) | | | | | --- | --- | | * `std::chrono::ambiguous_local_time` * `std::chrono::nonexistent_local_time` * `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")` | (since C++20) | ![std-runtime error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `runtime_error` object with the given message (public member function) | | operator= | replaces the `runtime_error` object (public member function) | | what | returns the explanatory string (public member function) | std::runtime\_error::runtime\_error ------------------------------------ | | | | | --- | --- | --- | | ``` runtime_error( const std::string& what_arg ); ``` | (1) | | | ``` runtime_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` runtime_error( const runtime_error& other ); ``` | (until C++11) | | ``` runtime_error( const runtime_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::runtime_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::runtime_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::runtime\_error::operator= ------------------------------- | | | | | --- | --- | --- | | ``` runtime_error& operator=( const runtime_error& other ); ``` | | (until C++11) | | ``` runtime_error& operator=( const runtime_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::runtime_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::runtime\_error::what -------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp std::rethrow_exception std::rethrow\_exception ======================= | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` [[noreturn]] void rethrow_exception( std::exception_ptr p ); ``` | | (since C++11) | Throws the previously captured exception object referred-to by the exception pointer `p`, or a copy of that object. It is unspecified whether a copy is made. If a copy is made, the storage for it is allocated in an unspecified way. The behavior is undefined if `p` is null. ### Parameters | | | | | --- | --- | --- | | p | - | non-null `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` | ### Return value (none). ### Exceptions The exception object referred-to by `p` if no copy is made. Otherwise, a copy of such exception object if the implementation successfully copied the exception object. Otherwise, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` or the exception thrown when copying the exception object, if allocation or copying fails, respectively. ### Notes Before [P1675R2](https://wg21.link/P1675R2), `rethrow_exception` was not allowed to copy the exception object, which is unimplementable on some platforms where exception objects are allocated on the stack. ### Example ``` #include <iostream> #include <string> #include <exception> #include <stdexcept> void handle_eptr(std::exception_ptr eptr) // passing by value is ok { try { if (eptr) { std::rethrow_exception(eptr); } } catch(const std::exception& e) { std::cout << "Caught exception \"" << e.what() << "\"\n"; } } int main() { std::exception_ptr eptr; try { std::string().at(1); // this generates an std::out_of_range } catch(...) { eptr = std::current_exception(); // capture } handle_eptr(eptr); } // destructor for std::out_of_range called here, when the eptr is destructed ``` Possible output: ``` Caught exception "basic_string::at" ``` ### See also | | | | --- | --- | | [exception\_ptr](exception_ptr "cpp/error/exception ptr") (C++11) | shared pointer type for handling exception objects (typedef) | | [current\_exception](current_exception "cpp/error/current exception") (C++11) | captures the current exception in a `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` (function) | cpp std::underflow_error std::underflow\_error ===================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class underflow_error; ``` | | | Defines a type of object to be thrown as exception. It may be used to report arithmetic underflow errors (that is, situations where the result of a computation is a subnormal floating-point value). The standard library components do not throw this exception (mathematical functions report underflow errors as specified in `[math\_errhandling](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling")`). Third-party libraries, however, use this. For example, [boost.math](http://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/math_toolkit/error_handling.html) throws `std::underflow_error` if `boost::math::policies::throw_on_error` is enabled (the default setting). ![std-underflow error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `underflow_error` object with the given message (public member function) | | operator= | replaces the `underflow_error` object (public member function) | | what | returns the explanatory string (public member function) | std::underflow\_error::underflow\_error ---------------------------------------- | | | | | --- | --- | --- | | ``` underflow_error( const std::string& what_arg ); ``` | (1) | | | ``` underflow_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` underflow_error( const underflow_error& other ); ``` | (until C++11) | | ``` underflow_error( const underflow_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::underflow_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::underflow_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::underflow\_error::operator= --------------------------------- | | | | | --- | --- | --- | | ``` underflow_error& operator=( const underflow_error& other ); ``` | | (until C++11) | | ``` underflow_error& operator=( const underflow_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::underflow_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::underflow\_error::what ---------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::runtime\_error](runtime_error "cpp/error/runtime error") ------------------------------------------------------------------------------- Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
programming_docs
cpp errno errno ===== | Defined in header `[<cerrno>](../header/cerrno "cpp/header/cerrno")` | | | | --- | --- | --- | | ``` #define errno /*implementation-defined*/ ``` | | | `errno` is a preprocessor macro used for error indication. It expands to a static (until C++11) thread-local (since C++11) modifiable lvalue of type `int`. Several standard library functions indicate errors by writing positive integers to `errno`. Typically, the value of `errno` is set to one of the error codes, listed in `<cerrno>` as macro constants that begin with the letter `E`, followed by uppercase letters or digits. The value of `errno` is `​0​` at program startup, and although library functions are allowed to write positive integers to `errno` whether or not an error occurred, library functions never store `​0​` in `errno`. ### Example ``` #include <iostream> #include <cmath> #include <cerrno> #include <cstring> #include <clocale> int main() { double not_a_number = std::log(-1.0); std::cout << not_a_number << '\n'; if (errno == EDOM) { std::cout << "log(-1) failed: " << std::strerror(errno) << '\n'; std::setlocale(LC_MESSAGES, "de_DE.utf8"); std::cout << "Or, in German, " << std::strerror(errno) << '\n'; } } ``` Possible output: ``` nan log(-1) failed: Numerical argument out of domain Or, in German, Das numerische Argument ist ausserhalb des Definitionsbereiches ``` ### 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 310](https://cplusplus.github.io/LWG/issue310) | C++98 | it is unspecified whether errno is a macro or an identifier with external linkage | errno must be macro | ### See also | | | | --- | --- | | [E2BIG, EACCES, ..., EXDEV](errno_macros "cpp/error/errno macros") | macros for standard POSIX-compatible error conditions (macro constant) | | [perror](../io/c/perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [strerror](../string/byte/strerror "cpp/string/byte/strerror") | returns a text version of a given error code (function) | | [C documentation](https://en.cppreference.com/w/c/error/errno "c/error/errno") for `errno` | cpp std::exception std::exception ============== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` class exception; ``` | | | Provides consistent interface to handle errors through the [throw expression](../language/throw "cpp/language/throw"). All exceptions generated by the standard library inherit from `std::exception`. * [`logic_error`](logic_error "cpp/error/logic error") + [`invalid_argument`](invalid_argument "cpp/error/invalid argument") + [`domain_error`](domain_error "cpp/error/domain error") + [`length_error`](length_error "cpp/error/length error") + [`out_of_range`](out_of_range "cpp/error/out of range") + [`future_error`](../thread/future_error "cpp/thread/future error")(C++11) * [`runtime_error`](runtime_error "cpp/error/runtime error") * [`range_error`](range_error "cpp/error/range error") * [`overflow_error`](overflow_error "cpp/error/overflow error") * [`underflow_error`](underflow_error "cpp/error/underflow error") * [`regex_error`](../regex/regex_error "cpp/regex/regex error")(C++11) * [`system_error`](system_error "cpp/error/system error")(C++11) + [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure")(C++11) + [`filesystem::filesystem_error`](../filesystem/filesystem_error "cpp/filesystem/filesystem error")(C++17) * [`tx_exception`](tx_exception "cpp/error/tx exception")(TM TS) * [`nonexistent_local_time`](../chrono/nonexistent_local_time "cpp/chrono/nonexistent local time")(C++20) * [`ambiguous_local_time`](../chrono/ambiguous_local_time "cpp/chrono/ambiguous local time")(C++20) * [`format_error`](../utility/format/format_error "cpp/utility/format/format error")(C++20) * [`bad_typeid`](../types/bad_typeid "cpp/types/bad typeid") * [`bad_cast`](../types/bad_cast "cpp/types/bad cast") + [`bad_any_cast`](../utility/any/bad_any_cast "cpp/utility/any/bad any cast")(C++17) * [`bad_optional_access`](../utility/optional/bad_optional_access "cpp/utility/optional/bad optional access")(C++17) * [`bad_expected_access`](../utility/expected/bad_expected_access "cpp/utility/expected/bad expected access")(C++23) * [`bad_weak_ptr`](../memory/bad_weak_ptr "cpp/memory/bad weak ptr")(C++11) * [`bad_function_call`](../utility/functional/bad_function_call "cpp/utility/functional/bad function call")(C++11) * [`bad_alloc`](../memory/new/bad_alloc "cpp/memory/new/bad alloc") + [`bad_array_new_length`](../memory/new/bad_array_new_length "cpp/memory/new/bad array new length")(C++11) * [`bad_exception`](bad_exception "cpp/error/bad exception") * [`ios_base::failure`](../io/ios_base/failure "cpp/io/ios base/failure")(until C++11) * [`bad_variant_access`](../utility/variant/bad_variant_access "cpp/utility/variant/bad variant access")(C++17) ### Member functions | | | | --- | --- | | [(constructor)](exception/exception "cpp/error/exception/exception") | constructs the exception object (public member function) | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function) | | [operator=](exception/operator= "cpp/error/exception/operator=") | copies exception object (public member function) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function) | cpp std::generic_category std::generic\_category ====================== | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` const std::error_category& generic_category() noexcept; ``` | | (since C++11) | Obtains a reference to the static error category object for generic errors. The object is required to override the virtual function `error_category::name()` to return a pointer to the string `"generic"`. It is used to identify error conditions that correspond to the POSIX `[errno](errno "cpp/error/errno")` codes. ### Parameters (none). ### Return value A reference to the static object of unspecified runtime type, derived from `[std::error\_category](error_category "cpp/error/error category")`. ### Example ``` #include <iostream> #include <system_error> #include <cerrno> #include <string> int main() { std::error_condition econd = std::generic_category().default_error_condition(EDOM); std::cout << "Category: " << econd.category().name() << '\n' << "Value: " << econd.value() << '\n' << "Message: " << econd.message() << '\n'; } ``` Output: ``` Category: generic Value: 33 Message: Numerical argument out of domain ``` ### See also | | | | --- | --- | | [system\_category](system_category "cpp/error/system category") (C++11) | identifies the operating system error category (function) | | [errc](errc "cpp/error/errc") (C++11) | the `[std::error\_condition](error_condition "cpp/error/error condition")` enumeration listing all standard [`<cerrno>`](../header/cerrno "cpp/header/cerrno") macro constants (class) | cpp std::bad_exception std::bad\_exception =================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` class bad_exception; ``` | | | `std::bad_exception` is the type of the exception thrown by the C++ runtime in the following situations: | | | | --- | --- | | * If `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` stores a copy of the caught exception and if the copy constructor of the exception object caught by `[std::current\_exception](current_exception "cpp/error/current exception")` throws an exception, the captured exception is an instance of `std::bad_exception`. | (since C++11) | | * If a [dynamic exception specification](../language/except_spec "cpp/language/except spec") is violated and `[std::unexpected](unexpected "cpp/error/unexpected")` throws or rethrows an exception that still violates the exception specification, but the exception specification allows `std::bad_exception`, `std::bad_exception` is thrown. | (until C++17) | ![std-bad exception-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | [(constructor)](bad_exception/bad_exception "cpp/error/bad exception/bad exception") | constructs the `bad_exception` object (public member function) | | [operator=](bad_exception/operator= "cpp/error/bad exception/operator=") | copies the object (public member function) | | [what](bad_exception/what "cpp/error/bad exception/what") [virtual] | returns the explanatory string (virtual public member function) | Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ``` #include <iostream> #include <exception> #include <stdexcept> void my_unexp() { throw; } void test() throw(std::bad_exception) { throw std::runtime_error("test"); } int main() { std::set_unexpected(my_unexp); try { test(); } catch(const std::bad_exception& e) { std::cerr << "Caught " << e.what() << '\n'; } } ``` Possible output: ``` Caught std::bad_exception ``` cpp assert assert ====== | Defined in header `[<cassert>](../header/cassert "cpp/header/cassert")` | | | | --- | --- | --- | | ``` #ifdef NDEBUG # define assert(condition) ((void)0) #else # define assert(condition) /*implementation defined*/ #endif ``` | | | The definition of the macro `assert` depends on another macro, `NDEBUG`, which is not defined by the standard library. If `NDEBUG` is defined as a macro name at the point in the source code where [`<cassert>`](../header/cassert "cpp/header/cassert") or `<assert.h>` is included, then `assert` does nothing. If `NDEBUG` is not defined, then `assert` checks if its argument (which must have scalar type) compares equal to zero. If it does, `assert` outputs implementation-specific diagnostic information on the standard error output and calls `[std::abort](../utility/program/abort "cpp/utility/program/abort")`. The diagnostic information is required to include the text of `expression`, as well as the values of the [predefined variable `__func__`](../language/function#func "cpp/language/function") and (since C++11) the [predefined macros](../preprocessor/replace "cpp/preprocessor/replace") `__FILE__` and `__LINE__`. | | | | --- | --- | | The expression `assert(E)` is guaranteed to be a [constant subexpression](../language/constant_expression "cpp/language/constant expression"), if either.* `NDEBUG` is defined at the point where `assert` is last defined or redefined (i.e., where the header `<cassert>` or `<assert.h>` was last included); or * `E`, contextually converted to `bool`, is a constant subexpression that evaluates to `true`. | (since C++17) | ### Parameters | | | | | --- | --- | --- | | condition | - | expression of scalar type | ### Return value (none). ### Notes Because `assert` is a [function-like macro](../preprocessor/replace "cpp/preprocessor/replace"), commas anywhere in condition that are not protected by parentheses are interpreted as macro argument separators. Such commas are often found in template argument lists and list-initialization: ``` assert(std::is_same_v<int, int>); // error: assert does not take two arguments assert((std::is_same_v<int, int>)); // OK: one argument static_assert(std::is_same_v<int, int>); // OK: not a macro std::complex<double> c; assert(c == std::complex<double>{0, 0}); // error assert((c == std::complex<double>{0, 0})); // OK ``` There is no standardized interface to add an additional message to `assert` errors. A portable way to include one is to use a [comma operator](../language/operator_other#Built-in_comma_operator "cpp/language/operator other") provided it has not been [overloaded](../language/operators "cpp/language/operators"), or use `&&` with a string literal: ``` assert(("There are five lights", 2 + 2 == 5)); assert( (2 + 2 == 5) && "There are five lights"); ``` The implementation of `assert` in [Microsoft CRT](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/assert-macro-assert-wassert?view=msvc-160) does not conform to C++11 and later revisions, because its underlying function (`_wassert`) takes neither `__func__` nor an equivalent replacement. ### Example ``` #include <iostream> // uncomment to disable assert() // #define NDEBUG #include <cassert> // Use (void) to silence unused warnings. #define assertm(exp, msg) assert(((void)msg, exp)) int main() { assert(2+2==4); std::cout << "Checkpoint #1\n"; assert((void("void helps to avoid 'unused value' warning"), 2*2==4)); std::cout << "Checkpoint #2\n"; assert((010+010==16) && "Yet another way to add an assert message"); std::cout << "Checkpoint #3\n"; assertm((2+2)%3==1, "Expect expected"); std::cout << "Checkpoint #4\n"; assertm(2+2==5, "There are five lights"); // assertion fails std::cout << "Execution continues past the last assert\n"; // No } ``` Possible output: ``` Checkpoint #1 Checkpoint #2 Checkpoint #3 Checkpoint #4 main.cpp:23: int main(): Assertion `((void)"There are five lights", 2+2==5)' failed. Aborted ``` ### See also | | | | --- | --- | | [`static_assert` declaration](../language/static_assert "cpp/language/static assert")(C++11) | performs compile-time assertion checking | | [abort](../utility/program/abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [C documentation](https://en.cppreference.com/w/c/error/assert "c/error/assert") for `assert` | cpp std::make_exception_ptr std::make\_exception\_ptr ========================= | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` template< class E > std::exception_ptr make_exception_ptr( E e ) noexcept; ``` | | (since C++11) | Creates an `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` that holds a reference to a copy of `e`. This is done as if executing the following code: ``` try { throw e; } catch(...) { return std::current_exception(); } ``` ### Parameters (none). ### Return value An instance of `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` holding a reference to the copy of `e`, or to an instance of `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` or to an instance of `[std::bad\_exception](bad_exception "cpp/error/bad exception")` (see `[std::current\_exception](current_exception "cpp/error/current exception")`). ### Notes The parameter is passed by value and is subject to slicing. ### See also | | | | --- | --- | | [current\_exception](current_exception "cpp/error/current exception") (C++11) | captures the current exception in a `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` (function) | cpp std::terminate_handler std::terminate\_handler ======================= | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` typedef void (*terminate_handler)(); ``` | | | `std::terminate_handler` is the function pointer type (pointer to function that takes no arguments and returns void), which is installed and queried by the functions `[std::set\_terminate](set_terminate "cpp/error/set terminate")` and `[std::get\_terminate](get_terminate "cpp/error/get terminate")` and called by `[std::terminate](terminate "cpp/error/terminate")`. The C++ implementation provides a default `std::terminate_handler` function, which calls `[std::abort](http://en.cppreference.com/w/cpp/utility/program/abort)()`. If the null pointer value is installed (by means of `[std::set\_terminate](set_terminate "cpp/error/set terminate")`), the implementation may restore the default handler instead. ### See also | | | | --- | --- | | [terminate](terminate "cpp/error/terminate") | function called when exception handling fails (function) | | [set\_terminate](set_terminate "cpp/error/set terminate") | changes the function to be called by `[std::terminate](terminate "cpp/error/terminate")` (function) | | [get\_terminate](get_terminate "cpp/error/get terminate") (C++11) | obtains the current terminate\_handler (function) | cpp std::errc std::errc ========= | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` enum class errc; ``` | | (since C++11) | The scoped enumeration `std::errc` defines the values of portable error conditions that correspond to the POSIX error codes. ### Member constants | Constant | Equivalent POSIX Error | | --- | --- | | `address_family_not_supported` | EAFNOSUPPORT | | `address_in_use` | EADDRINUSE | | `address_not_available` | EADDRNOTAVAIL | | `already_connected` | EISCONN | | `argument_list_too_long` | E2BIG | | `argument_out_of_domain` | EDOM | | `bad_address` | EFAULT | | `bad_file_descriptor` | EBADF | | `bad_message` | EBADMSG | | `broken_pipe` | EPIPE | | `connection_aborted` | ECONNABORTED | | `connection_already_in_progress` | EALREADY | | `connection_refused` | ECONNREFUSED | | `connection_reset` | ECONNRESET | | `cross_device_link` | EXDEV | | `destination_address_required` | EDESTADDRREQ | | `device_or_resource_busy` | EBUSY | | `directory_not_empty` | ENOTEMPTY | | `executable_format_error` | ENOEXEC | | `file_exists` | EEXIST | | `file_too_large` | EFBIG | | `filename_too_long` | ENAMETOOLONG | | `function_not_supported` | ENOSYS | | `host_unreachable` | EHOSTUNREACH | | `identifier_removed` | EIDRM | | `illegal_byte_sequence` | EILSEQ | | `inappropriate_io_control_operation` | ENOTTY | | `interrupted` | EINTR | | `invalid_argument` | EINVAL | | `invalid_seek` | ESPIPE | | `io_error` | EIO | | `is_a_directory` | EISDIR | | `message_size` | EMSGSIZE | | `network_down` | ENETDOWN | | `network_reset` | ENETRESET | | `network_unreachable` | ENETUNREACH | | `no_buffer_space` | ENOBUFS | | `no_child_process` | ECHILD | | `no_link` | ENOLINK | | `no_lock_available` | ENOLCK | | `no_message_available` | ENODATA | | `no_message` | ENOMSG | | `no_protocol_option` | ENOPROTOOPT | | `no_space_on_device` | ENOSPC | | `no_stream_resources` | ENOSR | | `no_such_device_or_address` | ENXIO | | `no_such_device` | ENODEV | | `no_such_file_or_directory` | ENOENT | | `no_such_process` | ESRCH | | `not_a_directory` | ENOTDIR | | `not_a_socket` | ENOTSOCK | | `not_a_stream` | ENOSTR | | `not_connected` | ENOTCONN | | `not_enough_memory` | ENOMEM | | `not_supported` | ENOTSUP | | `operation_canceled` | ECANCELED | | `operation_in_progress` | EINPROGRESS | | `operation_not_permitted` | EPERM | | `operation_not_supported` | EOPNOTSUPP | | `operation_would_block` | EWOULDBLOCK | | `owner_dead` | EOWNERDEAD | | `permission_denied` | EACCES | | `protocol_error` | EPROTO | | `protocol_not_supported` | EPROTONOSUPPORT | | `read_only_file_system` | EROFS | | `resource_deadlock_would_occur` | EDEADLK | | `resource_unavailable_try_again` | EAGAIN | | `result_out_of_range` | ERANGE | | `state_not_recoverable` | ENOTRECOVERABLE | | `stream_timeout` | ETIME | | `text_file_busy` | ETXTBSY | | `timed_out` | ETIMEDOUT | | `too_many_files_open_in_system` | ENFILE | | `too_many_files_open` | EMFILE | | `too_many_links` | EMLINK | | `too_many_symbolic_link_levels` | ELOOP | | `value_too_large` | EOVERFLOW | | `wrong_protocol_type` | EPROTOTYPE | ### Non-member functions | | | | --- | --- | | [make\_error\_code(std::errc)](errc/make_error_code "cpp/error/errc/make error code") (C++11) | constructs an `std::errc` error code (function) | | [make\_error\_condition(std::errc)](errc/make_error_condition "cpp/error/errc/make error condition") (C++11) | constructs an `std::errc` error condition (function) | ### Helper classes | | | | --- | --- | | [is\_error\_condition\_enum<std::errc>](errc/is_error_condition_enum "cpp/error/errc/is error condition enum") (C++11) | extends the type trait `[std::is\_error\_condition\_enum](error_condition/is_error_condition_enum "cpp/error/error condition/is error condition enum")` to identify `std::errc` values as error conditions (function template) | ### Example ``` #include <iostream> #include <system_error> #include <thread> int main() { try { std::thread().detach(); // detaching a not-a-thread } catch (const std::system_error& e) { std::cout << "Caught a system_error\n"; if(e.code() == std::errc::invalid_argument) std::cout << "The error condition is std::errc::invalid_argument\n"; std::cout << "the error description is " << e.what() << '\n'; } } ``` Possible output: ``` Caught a system_error The error condition is std::errc::invalid_argument the error description is Invalid argument ``` ### See also | | | | --- | --- | | [error\_code](error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [error\_condition](error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) |
programming_docs
cpp std::system_category std::system\_category ===================== | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` const std::error_category& system_category() noexcept; ``` | | (since C++11) | Obtains a reference to the static error category object for errors reported by the operating system. The object is required to override the virtual function `[std::error\_category::name()](error_category/name "cpp/error/error category/name")` to return a pointer to the string `"system"`. It is also required to override the virtual function `[std::error\_category::default\_error\_condition()](error_category/default_error_condition "cpp/error/error category/default error condition")` to map the error codes that match POSIX `[errno](errno "cpp/error/errno")` values to `[std::generic\_category](generic_category "cpp/error/generic category")`. ### Parameters (none). ### Return value A reference to the static object of unspecified runtime type, derived from `[std::error\_category](error_category "cpp/error/error category")`. ### Example ``` #include <iomanip> #include <iostream> #include <string> #include <system_error> int main() { for (int const code : {EDOM, 10001}) { const std::error_condition econd = std::system_category().default_error_condition(code); std::cout << "Category: " << econd.category().name() << '\n' << "Value: " << econd.value() << '\n' << "Message: " << econd.message() << "\n\n"; } } ``` Possible output: ``` Category: generic Value: 33 Message: Numerical argument out of domain Category: system Value: 10001 Message: Unknown error 10001 ``` ### See also | | | | --- | --- | | [generic\_category](generic_category "cpp/error/generic category") (C++11) | identifies the generic error category (function) | | [errc](errc "cpp/error/errc") (C++11) | the `[std::error\_condition](error_condition "cpp/error/error condition")` enumeration listing all standard [`<cerrno>`](../header/cerrno "cpp/header/cerrno") macro constants (class) | cpp std::throw_with_nested std::throw\_with\_nested ======================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` template< class T > [[noreturn]] void throw_with_nested( T&& t ); ``` | | (since C++11) | If `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<T>::type` is a non-final non-union class type that is neither `[std::nested\_exception](nested_exception "cpp/error/nested exception")` nor derived from `[std::nested\_exception](nested_exception "cpp/error/nested exception")`, throws an exception of an unspecified type that is publicly derived from both `[std::nested\_exception](nested_exception "cpp/error/nested exception")` and from `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<T>::type`, and constructed from `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`. The default constructor of the `nested_exception` base class calls `[std::current\_exception](current_exception "cpp/error/current exception")`, capturing the currently handled exception object, if any, in a `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")`. Otherwise, throws `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)`. Requires that `[std::decay](http://en.cppreference.com/w/cpp/types/decay)<T>::type` is [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). ### Parameters | | | | | --- | --- | --- | | t | - | the exception object to throw | ### Return value (none). ### Example Demonstrates construction and recursion through a nested exception object. ``` #include <iostream> #include <stdexcept> #include <exception> #include <string> #include <fstream> // prints the explanatory string of an exception. If the exception is nested, // recurses to print the explanatory of the exception it holds void print_exception(const std::exception& e, int level = 0) { std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n'; try { std::rethrow_if_nested(e); } catch(const std::exception& nestedException) { print_exception(nestedException, level+1); } catch(...) {} } // sample function that catches an exception and wraps it in a nested exception void open_file(const std::string& s) { try { std::ifstream file(s); file.exceptions(std::ios_base::failbit); } catch(...) { std::throw_with_nested( std::runtime_error("Couldn't open " + s) ); } } // sample function that catches an exception and wraps it in a nested exception void run() { try { open_file("nonexistent.file"); } catch(...) { std::throw_with_nested( std::runtime_error("run() failed") ); } } // runs the sample function above and prints the caught exception int main() { try { run(); } catch(const std::exception& e) { print_exception(e); } } ``` Possible output: ``` exception: run() failed exception: Couldn't open nonexistent.file exception: basic_ios::clear ``` ### See also | | | | --- | --- | | [nested\_exception](nested_exception "cpp/error/nested exception") (C++11) | a mixin type to capture and store current exceptions (class) | | [rethrow\_if\_nested](rethrow_if_nested "cpp/error/rethrow if nested") (C++11) | throws the exception from a `[std::nested\_exception](nested_exception "cpp/error/nested exception")` (function template) | cpp std::range_error std::range\_error ================= | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class range_error; ``` | | | Defines a type of object to be thrown as exception. It can be used to report range errors (that is, situations where a result of a computation cannot be represented by the destination type). The only standard library components that throw this exception are `[std::wstring\_convert::from\_bytes](../locale/wstring_convert/from_bytes "cpp/locale/wstring convert/from bytes")` and `[std::wstring\_convert::to\_bytes](../locale/wstring_convert/to_bytes "cpp/locale/wstring convert/to bytes")`. The mathematical functions in the standard library components do not throw this exception (mathematical functions report range errors as specified in `[math\_errhandling](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling")`). ![std-range error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `range_error` object with the given message (public member function) | | operator= | replaces the `range_error` object (public member function) | | what | returns the explanatory string (public member function) | std::range\_error::range\_error -------------------------------- | | | | | --- | --- | --- | | ``` range_error( const std::string& what_arg ); ``` | (1) | | | ``` range_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` range_error( const range_error& other ); ``` | (until C++11) | | ``` range_error( const range_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::range_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::range_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::range\_error::operator= ----------------------------- | | | | | --- | --- | --- | | ``` range_error& operator=( const range_error& other ); ``` | | (until C++11) | | ``` range_error& operator=( const range_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::range_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::range\_error::what ------------------------ | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::runtime\_error](runtime_error "cpp/error/runtime error") ------------------------------------------------------------------------------- Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp std::get_unexpected std::get\_unexpected ==================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` std::unexpected_handler get_unexpected() noexcept; ``` | | (since C++11) (deprecated) (removed in C++17) | Returns the currently installed `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")`, which may be a null pointer. This function is thread-safe. Prior call to `std::set_unexpected` *synchronizes-with* (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) the subsequent calls to this function. ### Parameters (none). ### Return value The currently installed `[std::unexpected\_handler](unexpected_handler "cpp/error/unexpected handler")`. ### See also | | | | --- | --- | | [unexpected\_handler](unexpected_handler "cpp/error/unexpected handler") (removed in C++17) | the type of the function called by `[std::unexpected](unexpected "cpp/error/unexpected")` (typedef) | | [set\_unexpected](set_unexpected "cpp/error/set unexpected") (removed in C++17) | changes the function to be called by `[std::unexpected](unexpected "cpp/error/unexpected")` (function) | cpp std::current_exception std::current\_exception ======================= | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` std::exception_ptr current_exception() noexcept; ``` | | (since C++11) | If called during exception handling (typically, in a `catch` clause), captures the current exception object and creates an `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` that holds either a copy or a reference to that exception object (depending on the implementation). The referenced object remains valid at least as long as there is an `exception_ptr` object that refers to it. If the implementation of this function requires a call to `new` and the call fails, the returned pointer will hold a reference to an instance of `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")`. If the implementation of this function requires copying the captured exception object and its copy constructor throws an exception, the returned pointer will hold a reference to the exception thrown. If the copy constructor of the thrown exception object also throws, the returned pointer may hold a reference to an instance of `[std::bad\_exception](bad_exception "cpp/error/bad exception")` to break the endless loop. If the function is called when no exception is being handled, an empty `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` is returned. ### Parameters (none). ### Return value An instance of `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` holding a reference to the exception object, or a copy of the exception object, or to an instance of `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` or to an instance of `[std::bad\_exception](bad_exception "cpp/error/bad exception")`. ### Notes On the implementations that follow Itanium C++ ABI (GCC, Clang, etc), exceptions are allocated on the heap when thrown (except for bad\_alloc in some cases), and this function simply creates the smart pointer referencing the previously-allocated object, On MSVC, exceptions are allocated on stack when thrown, and this function performs the heap allocation and copies the exception object. ### Example ``` #include <iostream> #include <string> #include <exception> #include <stdexcept> void handle_eptr(std::exception_ptr eptr) // passing by value is ok { try { if (eptr) { std::rethrow_exception(eptr); } } catch(const std::exception& e) { std::cout << "Caught exception \"" << e.what() << "\"\n"; } } int main() { std::exception_ptr eptr; try { std::string().at(1); // this generates an std::out_of_range } catch(...) { eptr = std::current_exception(); // capture } handle_eptr(eptr); } // destructor for std::out_of_range called here, when the eptr is destructed ``` Possible output: ``` Caught exception "basic_string::at" ``` ### See also | | | | --- | --- | | [exception\_ptr](exception_ptr "cpp/error/exception ptr") (C++11) | shared pointer type for handling exception objects (typedef) | | [rethrow\_exception](rethrow_exception "cpp/error/rethrow exception") (C++11) | throws the exception from an `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` (function) | | [make\_exception\_ptr](make_exception_ptr "cpp/error/make exception ptr") (C++11) | creates an `[std::exception\_ptr](exception_ptr "cpp/error/exception ptr")` from an exception object (function template) | | [uncaught\_exceptionuncaught\_exceptions](uncaught_exception "cpp/error/uncaught exception") (removed in C++20)(C++17) | checks if exception handling is currently in progress (function) | cpp std::domain_error std::domain\_error ================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class domain_error; ``` | | | Defines a type of object to be thrown as exception. It may be used by the implementation to report domain errors, that is, situations where the inputs are outside of the domain on which an operation is defined. The standard library components do not throw this exception (mathematical functions report domain errors as specified in `[math\_errhandling](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling")`). Third-party libraries, however, use this. For example, [boost.math](http://www.boost.org/doc/libs/1_55_0/libs/math/doc/html/math_toolkit/error_handling.html) throws `std::domain_error` if `boost::math::policies::throw_on_error` is enabled (the default setting). ![std-domain error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `domain_error` object with the given message (public member function) | | operator= | replaces the `domain_error` object (public member function) | | what | returns the explanatory string (public member function) | std::domain\_error::domain\_error ---------------------------------- | | | | | --- | --- | --- | | ``` domain_error( const std::string& what_arg ); ``` | (1) | | | ``` domain_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` domain_error( const domain_error& other ); ``` | (until C++11) | | ``` domain_error( const domain_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::domain_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::domain_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::domain\_error::operator= ------------------------------ | | | | | --- | --- | --- | | ``` domain_error& operator=( const domain_error& other ); ``` | | (until C++11) | | ``` domain_error& operator=( const domain_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::domain_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::domain\_error::what ------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::logic\_error](logic_error "cpp/error/logic error") ------------------------------------------------------------------------ Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) |
programming_docs
cpp std::exception_ptr std::exception\_ptr =================== | Defined in header `[<exception>](../header/exception "cpp/header/exception")` | | | | --- | --- | --- | | ``` typedef /*unspecified*/ exception_ptr; ``` | | (since C++11) | `std::exception_ptr` is a nullable pointer-like type that manages an exception object which has been thrown and captured with `[std::current\_exception](current_exception "cpp/error/current exception")`. An instance of `std::exception_ptr` may be passed to another function, possibly on another thread, where the exception may be rethrown and handled with a catch clause. A default-constructed `std::exception_ptr` is a null pointer; it does not point to an exception object. Two instances of `std::exception_ptr` compare equal only if they are both null or both point at the same exception object. `std::exception_ptr` is not implicitly convertible to any arithmetic, enumeration, or pointer type. It is contextually convertible to `bool`, and will evaluate to false if it is null, true otherwise. The exception object referenced by an `std::exception_ptr` remains valid as long as there remains at least one `std::exception_ptr` that is referencing it: `std::exception_ptr` is a shared-ownership smart pointer (note; this is in addition to the usual [exception object lifetime rules](../language/throw#The_exception_object "cpp/language/throw")). `std::exception_ptr` meets the requirements of [NullablePointer](../named_req/nullablepointer "cpp/named req/NullablePointer"). ### Example ``` #include <iostream> #include <string> #include <exception> #include <stdexcept> void handle_eptr(std::exception_ptr eptr) // passing by value is ok { try { if (eptr) { std::rethrow_exception(eptr); } } catch(const std::exception& e) { std::cout << "Caught exception \"" << e.what() << "\"\n"; } } int main() { std::exception_ptr eptr; try { std::string().at(1); // this generates an std::out_of_range } catch(...) { eptr = std::current_exception(); // capture } handle_eptr(eptr); } // destructor for std::out_of_range called here, when the eptr is destructed ``` Possible output: ``` Caught exception "basic_string::at" ``` ### See also | | | | --- | --- | | [make\_exception\_ptr](make_exception_ptr "cpp/error/make exception ptr") (C++11) | creates an `std::exception_ptr` from an exception object (function template) | | [current\_exception](current_exception "cpp/error/current exception") (C++11) | captures the current exception in a `std::exception_ptr` (function) | | [rethrow\_exception](rethrow_exception "cpp/error/rethrow exception") (C++11) | throws the exception from an `std::exception_ptr` (function) | cpp std::system_error std::system\_error ================== | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` class system_error; ``` | | (since C++11) | `std::system_error` is the type of the exception thrown by various library functions (typically the functions that interface with the OS facilities, e.g. the constructor of `[std::thread](../thread/thread "cpp/thread/thread")`) when the exception has an associated `[std::error\_code](error_code "cpp/error/error code")`, which may be reported. ![std-system error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | [(constructor)](system_error/system_error "cpp/error/system error/system error") | constructs the `system_error` object (public member function) | | [operator=](system_error/operator= "cpp/error/system error/operator=") | replaces the `system_error` object (public member function) | | [code](system_error/code "cpp/error/system error/code") | returns error code (public member function) | | [what](system_error/what "cpp/error/system error/what") [virtual] | returns an explanatory string (virtual public member function) | Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ``` #include <thread> #include <iostream> #include <system_error> int main() { try { std::thread().detach(); // attempt to detach a non-thread } catch(const std::system_error& e) { std::cout << "Caught system_error with code " << e.code() << " meaning " << e.what() << '\n'; } } ``` Possible output: ``` Caught system_error with code generic:22 meaning Invalid argument ``` cpp std::error_code std::error\_code ================ | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` class error_code; ``` | | (since C++11) | `std::error_code` is a platform-dependent error code. Each `std::error_code` object holds an error code originating from the operating system or some low-level interface and a pointer to an object of type `[std::error\_category](error_category "cpp/error/error category")`, which corresponds to the said interface. The error code values may be not unique across different error categories. ### Member functions | | | | --- | --- | | [(constructor)](error_code/error_code "cpp/error/error code/error code") | constructs an error code (public member function) | | [operator=](error_code/operator= "cpp/error/error code/operator=") | assigns another error code (public member function) | | [assign](error_code/assign "cpp/error/error code/assign") | assigns another error code (public member function) | | Modifiers | | [clear](error_code/clear "cpp/error/error code/clear") | sets the error\_code to value 0 in system\_category (public member function) | | Observers | | [value](error_code/value "cpp/error/error code/value") | obtains the value of the error\_code (public member function) | | [category](error_code/category "cpp/error/error code/category") | obtains the error\_category for this error\_code (public member function) | | [default\_error\_condition](error_code/default_error_condition "cpp/error/error code/default error condition") | obtains the error\_condition for this error\_code (public member function) | | [message](error_code/message "cpp/error/error code/message") | obtains the explanatory string for this error\_code (public member function) | | [operator bool](error_code/operator_bool "cpp/error/error code/operator bool") | checks if the value is non-zero (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=>](error_code/operator_cmp "cpp/error/error code/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares two `error_code`s (function) | | [operator<<](error_code/operator_ltlt "cpp/error/error code/operator ltlt") | outputs the value and the category name to an output stream (function) | ### Helper classes | | | | --- | --- | | [is\_error\_code\_enum](error_code/is_error_code_enum "cpp/error/error code/is error code enum") (C++11) | identifies a class as an error\_code enumeration (class template) | | [std::hash<std::error\_code>](error_code/hash "cpp/error/error code/hash") (C++11) | hash support for `std::error_code` (class template specialization) | ### See also | | | | --- | --- | | [error\_condition](error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | | [error\_category](error_category "cpp/error/error category") (C++11) | base class for error categories (class) | | [make\_error\_code(std::errc)](errc/make_error_code "cpp/error/errc/make error code") (C++11) | constructs an `[std::errc](errc "cpp/error/errc")` error code (function) | cpp std::tx_exception std::tx\_exception ================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` template< class T > class tx_exception : public std::runtime_error; ``` | | (TM TS) | Defines an exception type that can be used to cancel and roll back an atomic transaction initiated by the keyword [`atomic_cancel`](../language/transactional_memory "cpp/language/transactional memory"). If `T` is not [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), the program that specializes `std::tx_exception<T>` is ill-formed. ### Member functions std::tx\_exception::tx\_exception ---------------------------------- | | | | | --- | --- | --- | | ``` explicit tx_exception( T value ) transaction_safe; ``` | (1) | (TM TS) | | ``` tx_exception( T value, const std::string& what_arg ) transaction_safe; ``` | (2) | (TM TS) | | ``` tx_exception( T value, const char* what_arg ) transaction_safe; ``` | (3) | (TM TS) | | ``` tx_exception( const tx_exception& other ) transaction_safe noexcept; ``` | (4) | (TM TS) | 1-3) Constructs the exception object with `what_arg` as explanatory string that can be accessed through `what()` and `value` as the object that can be accessed through `get()`. 4) Copy constructor. If `*this` and `other` both have dynamic type `std::tx_exception<T>` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | value | - | payload object | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-3) May throw implementation-defined exceptions. std::tx\_exception::operator= ------------------------------ | | | | | --- | --- | --- | | ``` tx_exception& operator=( const tx_exception& other ) transaction_safe noexcept; ``` | | (TM TS) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::tx_exception<T>` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::tx\_exception::get ------------------------ | | | | | --- | --- | --- | | ``` T get() const transaction_safe; ``` | | (TM TS) | Returns the payload object object held by the exception object. ### Exceptions May throw implementation-defined exceptions. std::tx\_exception::what ------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const transaction_safe_dynamic noexcept; ``` | | (TM TS) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. Inherited from [std::runtime\_error](runtime_error "cpp/error/runtime error") ------------------------------------------------------------------------------- Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp std::overflow_error std::overflow\_error ==================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class overflow_error; ``` | | | Defines a type of object to be thrown as exception. It can be used to report arithmetic overflow errors (that is, situations where a result of a computation is too large for the destination type). The only standard library components that throw this exception are `[std::bitset::to\_ulong](../utility/bitset/to_ulong "cpp/utility/bitset/to ulong")` and `[std::bitset::to\_ullong](../utility/bitset/to_ullong "cpp/utility/bitset/to ullong")`. The mathematical functions of the standard library components do not throw this exception (mathematical functions report overflow errors as specified in `[math\_errhandling](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling")`). Third-party libraries, however, use this. For example, [boost.math](http://www.boost.org/doc/libs/1_55_0/libs/math/doc/html/math_toolkit/error_handling.html) throws `std::overflow_error` if `boost::math::policies::throw_on_error` is enabled (the default setting). ![std-overflow error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `overflow_error` object with the given message (public member function) | | operator= | replaces the `overflow_error` object (public member function) | | what | returns the explanatory string (public member function) | std::overflow\_error::overflow\_error -------------------------------------- | | | | | --- | --- | --- | | ``` overflow_error( const std::string& what_arg ); ``` | (1) | | | ``` overflow_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` overflow_error( const overflow_error& other ); ``` | (until C++11) | | ``` overflow_error( const overflow_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::overflow_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::overflow_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::overflow\_error::operator= -------------------------------- | | | | | --- | --- | --- | | ``` overflow_error& operator=( const overflow_error& other ); ``` | | (until C++11) | | ``` overflow_error& operator=( const overflow_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::overflow_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::overflow\_error::what --------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::runtime\_error](runtime_error "cpp/error/runtime error") ------------------------------------------------------------------------------- Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp std::invalid_argument std::invalid\_argument ====================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class invalid_argument; ``` | | | Defines a type of object to be thrown as exception. It reports errors that arise because an argument value has not been accepted. This exception is thrown by `[std::bitset::bitset](../utility/bitset/bitset "cpp/utility/bitset/bitset")`, and the `[std::stoi](../string/basic_string/stol "cpp/string/basic string/stol")` and `[std::stof](../string/basic_string/stof "cpp/string/basic string/stof")` families of functions. ![std-invalid argument-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `invalid_argument` object with the given message (public member function) | | operator= | replaces the `invalid_argument` object (public member function) | | what | returns the explanatory string (public member function) | std::invalid\_argument::invalid\_argument ------------------------------------------ | | | | | --- | --- | --- | | ``` invalid_argument( const std::string& what_arg ); ``` | (1) | | | ``` invalid_argument( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` invalid_argument( const invalid_argument& other ); ``` | (until C++11) | | ``` invalid_argument( const invalid_argument& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::invalid_argument` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::invalid_argument` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::invalid\_argument::operator= ---------------------------------- | | | | | --- | --- | --- | | ``` invalid_argument& operator=( const invalid_argument& other ); ``` | | (until C++11) | | ``` invalid_argument& operator=( const invalid_argument& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::invalid_argument` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::invalid\_argument::what ----------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::logic\_error](logic_error "cpp/error/logic error") ------------------------------------------------------------------------ Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Notes The purpose of this exception type is similar to the error condition `[std::errc::invalid\_argument](errc "cpp/error/errc")` (thrown in `[std::system\_error](system_error "cpp/error/system error")` from member functions of `[std::thread](../thread/thread "cpp/thread/thread")`) and the related errno constant `[EINVAL](errno_macros "cpp/error/errno macros")`. ### Example ``` #include <bitset> #include <iostream> #include <stdexcept> #include <string> int main() { try { std::bitset<4>{"012"}; // Throws: only '0' or '1' expected } catch (std::invalid_argument const& ex) { std::cout << "#1: " << ex.what() << '\n'; } try { [[maybe_unused]] int f = std::stoi("ABBA"); // Throws: no conversion } catch (std::invalid_argument const& ex) { std::cout << "#2: " << ex.what() << '\n'; } try { [[maybe_unused]] float f = std::stof("(3.14)"); // Throws: no conversion } catch (std::invalid_argument const& ex) { std::cout << "#3: " << ex.what() << '\n'; } } ``` Possible output: ``` #1: bitset string ctor has invalid argument #2: stoi: no conversion #3: stof: no conversion ```
programming_docs
cpp std::out_of_range std::out\_of\_range =================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class out_of_range; ``` | | | Defines a type of object to be thrown as exception. It reports errors that are consequence of attempt to access elements out of defined range. It may be thrown by the member functions of `[std::bitset](../utility/bitset "cpp/utility/bitset")` and `[std::basic\_string](../string/basic_string "cpp/string/basic string")`, by `[std::stoi](../string/basic_string/stol "cpp/string/basic string/stol")` and `[std::stod](../string/basic_string/stof "cpp/string/basic string/stof")` families of functions, and by the bounds-checked member access functions (e.g. `[std::vector::at](../container/vector/at "cpp/container/vector/at")` and `[std::map::at](../container/map/at "cpp/container/map/at")`). ![std-out of range-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `out_of_range` object with the given message (public member function) | | operator= | replaces the `out_of_range` object (public member function) | | what | returns the explanatory string (public member function) | std::out\_of\_range::out\_of\_range ------------------------------------ | | | | | --- | --- | --- | | ``` out_of_range( const std::string& what_arg ); ``` | (1) | | | ``` out_of_range( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` out_of_range( const out_of_range& other ); ``` | (until C++11) | | ``` out_of_range( const out_of_range& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::out_of_range` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::out_of_range` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::out\_of\_range::operator= ------------------------------- | | | | | --- | --- | --- | | ``` out_of_range& operator=( const out_of_range& other ); ``` | | (until C++11) | | ``` out_of_range& operator=( const out_of_range& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::out_of_range` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::out\_of\_range::what -------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::logic\_error](logic_error "cpp/error/logic error") ------------------------------------------------------------------------ Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Notes The standard error condition `[std::errc::result\_out\_of\_range](errc "cpp/error/errc")` typically indicates the condition where the result, rather than the input, is out of range, and is more closely related to `[std::range\_error](range_error "cpp/error/range error")` and `[ERANGE](errno_macros "cpp/error/errno macros")`. ### See also | | | | --- | --- | | [at](../string/basic_string/at "cpp/string/basic string/at") | accesses the specified character with bounds checking (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [at](../string/basic_string_view/at "cpp/string/basic string view/at") (C++17) | accesses the specified character with bounds checking (public member function of `std::basic_string_view<CharT,Traits>`) | | [at](../container/deque/at "cpp/container/deque/at") | access specified element with bounds checking (public member function of `std::deque<T,Allocator>`) | | [at](../container/vector/at "cpp/container/vector/at") | access specified element with bounds checking (public member function of `std::vector<T,Allocator>`) | | [at](../container/array/at "cpp/container/array/at") (C++11) | access specified element with bounds checking (public member function of `std::array<T,N>`) | cpp std::logic_error std::logic\_error ================= | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class logic_error; ``` | | | Defines a type of object to be thrown as exception. It reports errors that are a consequence of faulty logic within the program such as violating logical preconditions or class invariants and may be preventable. No standard library components throw this exception directly, but the exception types `[std::invalid\_argument](invalid_argument "cpp/error/invalid argument")`, `[std::domain\_error](domain_error "cpp/error/domain error")`, `[std::length\_error](length_error "cpp/error/length error")`, `[std::out\_of\_range](out_of_range "cpp/error/out of range")`, `[std::future\_error](../thread/future_error "cpp/thread/future error")`, and [`std::experimental::bad_optional_access`](https://en.cppreference.com/w/cpp/experimental/optional/bad_optional_access "cpp/experimental/optional/bad optional access") are derived from `std::logic_error`. ![std-logic error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `logic_error` object with the given message (public member function) | | operator= | replaces the `logic_error` object (public member function) | | what | returns the explanatory string (public member function) | std::logic\_error::logic\_error -------------------------------- | | | | | --- | --- | --- | | ``` logic_error( const std::string& what_arg ); ``` | (1) | | | ``` logic_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` logic_error( const logic_error& other ); ``` | (until C++11) | | ``` logic_error( const logic_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::logic_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::logic_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::logic\_error::operator= ----------------------------- | | | | | --- | --- | --- | | ``` logic_error& operator=( const logic_error& other ); ``` | | (until C++11) | | ``` logic_error& operator=( const logic_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::logic_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::logic\_error::what ------------------------ | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | cpp std::length_error std::length\_error ================== | Defined in header `[<stdexcept>](../header/stdexcept "cpp/header/stdexcept")` | | | | --- | --- | --- | | ``` class length_error; ``` | | | Defines a type of object to be thrown as exception. It reports errors that result from attempts to exceed implementation defined length limits for some object. This exception is thrown by member functions of `[std::basic\_string](../string/basic_string "cpp/string/basic string")` and `[std::vector::reserve](../container/vector/reserve "cpp/container/vector/reserve")`. ![std-length error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | (constructor) | constructs a new `length_error` object with the given message (public member function) | | operator= | replaces the `length_error` object (public member function) | | what | returns the explanatory string (public member function) | std::length\_error::length\_error ---------------------------------- | | | | | --- | --- | --- | | ``` length_error( const std::string& what_arg ); ``` | (1) | | | ``` length_error( const char* what_arg ); ``` | (2) | (since C++11) | | | (3) | | | ``` length_error( const length_error& other ); ``` | (until C++11) | | ``` length_error( const length_error& other ) noexcept; ``` | (since C++11) | 1-2) Constructs the exception object with `what_arg` as explanatory string that can be accessed through [`what()`](exception/what "cpp/error/exception/what"). 3) Copy constructor. If `*this` and `other` both have dynamic type `std::length_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | other | - | another exception object to copy | ### Exceptions 1-2) May throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` ### Notes Because copying `std::length_error` is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. std::length\_error::operator= ------------------------------ | | | | | --- | --- | --- | | ``` length_error& operator=( const length_error& other ); ``` | | (until C++11) | | ``` length_error& operator=( const length_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::length_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another exception object to assign with | ### Return value `*this`. std::length\_error::what ------------------------- | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The string is suitable for conversion and display as a `[std::wstring](../string/basic_string "cpp/string/basic string")`. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function (e.g. copy assignment operator) on the exception object is called. ### Notes Implementations are allowed but not required to override `what()`. Inherited from [std::logic\_error](logic_error "cpp/error/logic error") ------------------------------------------------------------------------ Inherited from [std::exception](exception "cpp/error/exception") ------------------------------------------------------------------ ### Member functions | | | | --- | --- | | [(destructor)](exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### See also | | | | --- | --- | | [resize](../string/basic_string/resize "cpp/string/basic string/resize") | changes the number of characters stored (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::error_condition std::error\_condition ===================== | Defined in header `[<system\_error>](../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` class error_condition; ``` | | (since C++11) | `std::error_condition` is a platform-independent error code. Like `[std::error\_code](error_code "cpp/error/error code")`, it is uniquely identified by an integer value and a `[std::error\_category](error_category "cpp/error/error category")`, but unlike `[std::error\_code](error_code "cpp/error/error code")`, the value is not platform-dependent. A typical implementation holds one integer data member (the value) and a pointer to an `[std::error\_category](error_category "cpp/error/error category")`. ### Member functions | | | | --- | --- | | [(constructor)](error_condition/error_condition "cpp/error/error condition/error condition") | constructs an `error_condition` (public member function) | | [operator=](error_condition/operator= "cpp/error/error condition/operator=") | replaces the contents (public member function) | | [assign](error_condition/assign "cpp/error/error condition/assign") | replaces the contents (public member function) | | [clear](error_condition/clear "cpp/error/error condition/clear") | sets the error\_condition to value 0 in generic\_category (public member function) | | [value](error_condition/value "cpp/error/error condition/value") | obtains the value of the error\_condition (public member function) | | [category](error_condition/category "cpp/error/error condition/category") | obtains the `error_category` for this `error_condition` (public member function) | | [message](error_condition/message "cpp/error/error condition/message") | obtains the explanatory string (public member function) | | [operator bool](error_condition/operator_bool "cpp/error/error condition/operator bool") | checks if the value is non-zero (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=>](error_condition/operator_cmp "cpp/error/error condition/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares `error_condition`s and `error_code`s (function) | ### Helper classes | | | | --- | --- | | [is\_error\_condition\_enum](error_condition/is_error_condition_enum "cpp/error/error condition/is error condition enum") (C++11) | identifies an enumeration as an `std::error_condition` (class template) | | [std::hash<std::error\_condition>](error_condition/hash "cpp/error/error condition/hash") (C++17) | hash support for `std::error_condition` (class template specialization) | ### See also | | | | --- | --- | | [error\_code](error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [error\_category](error_category "cpp/error/error category") (C++11) | base class for error categories (class) | | [make\_error\_condition(std::errc)](errc/make_error_condition "cpp/error/errc/make error condition") (C++11) | constructs an `[std::errc](errc "cpp/error/errc")` error condition (function) | cpp std::make_error_code(std::errc) std::make\_error\_code(std::errc) ================================= | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` std::error_code make_error_code( std::errc e ) noexcept; ``` | | (since C++11) | Creates error code value for errc enum `e`. Equivalent to `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)(static\_cast<int>(e), [std::generic\_category](http://en.cppreference.com/w/cpp/error/generic_category)())`. ### Parameters | | | | | --- | --- | --- | | e | - | error code enum to create error code for | ### Return value Error code corresponding to `e`. ### See also | | | | --- | --- | | [make\_error\_code(std::io\_errc)](../../io/io_errc/make_error_code "cpp/io/io errc/make error code") (C++11) | constructs an iostream error code (function) | | [make\_error\_code(std::future\_errc)](../../thread/future_errc/make_error_code "cpp/thread/future errc/make error code") (C++11) | constructs a future error code (function) | cpp std::make_error_condition(std::errc) std::make\_error\_condition(std::errc) ====================================== | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` std::error_condition make_error_condition( std::errc e ) noexcept; ``` | | (since C++11) | Creates an error condition for an `errc` value `e`. Sets the error code to `int(e)` and error category to `[std::generic\_category](../generic_category "cpp/error/generic category")`. ### Parameters | | | | | --- | --- | --- | | e | - | standard error code | ### Return value Error condition for `e`. ### Example ``` #include <system_error> #include <string> #include <iostream> int main() { auto err = std::make_error_condition(std::errc::invalid_argument); std::cout << err.message() << '\n'; } ``` Possible output: ``` Invalid argument ```
programming_docs
cpp std::bad_exception::bad_exception std::bad\_exception::bad\_exception =================================== | | | | | --- | --- | --- | | | (1) | | | ``` bad_exception() throw(); ``` | (until C++11) | | ``` bad_exception() noexcept; ``` | (since C++11) | | | (2) | | | ``` bad_exception( const bad_exception& other ) throw(); ``` | (until C++11) | | ``` bad_exception( const bad_exception& other ) noexcept; ``` | (since C++11) | Constructs new `bad_exception` object. 1) Default constructor. `what()` returns an implementation-defined string. 2) Copy constructor. Initializes the object with the contents of `other`. If `*this` and `other` both have dynamic type `std::bad_exception` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | other | - | `bad_exception` object to initialize with | cpp std::bad_exception::operator= std::bad\_exception::operator= ============================== | | | | | --- | --- | --- | | ``` bad_exception& operator=( const bad_exception& other ) throw(); ``` | | (until C++11) | | ``` bad_exception& operator=( const bad_exception& other ) noexcept; ``` | | (since C++11) | Assigns the contents of `other`. If `*this` and `other` both have dynamic type `std::exception` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. (since C++11). ### Parameters | | | | | --- | --- | --- | | other | - | another `bad_exception` object to assign | ### Return value `*this`. cpp std::bad_exception::what std::bad\_exception::what ========================= | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. cpp std::nested_exception::nested_exception std::nested\_exception::nested\_exception ========================================= | | | | | --- | --- | --- | | ``` nested_exception() noexcept; ``` | (1) | (since C++11) | | ``` nested_exception( const nested_exception& other ) noexcept = default; ``` | (2) | (since C++11) | Constructs new `nested_exception` object. 1) Default constructor. Stores an exception object obtained by calling `[std::current\_exception](http://en.cppreference.com/w/cpp/error/current_exception)()` within the new `nested_exception` object. 2) Copy constructor. Initializes the object with the exception stored in `other`. ### Parameters | | | | | --- | --- | --- | | other | - | nested exception to initialize the contents with | cpp std::nested_exception::nested_ptr std::nested\_exception::nested\_ptr =================================== | | | | | --- | --- | --- | | ``` std::exception_ptr nested_ptr() const noexcept; ``` | | (since C++11) | Returns a pointer to the stored exception, if any. ### Parameters (none). ### Return value (none). cpp std::nested_exception::~nested_exception std::nested\_exception::~nested\_exception ========================================== | | | | | --- | --- | --- | | ``` virtual ~nested_exception() = default; ``` | | (since C++11) | Destroys the nested exception object. cpp std::nested_exception::rethrow_nested std::nested\_exception::rethrow\_nested ======================================= | | | | | --- | --- | --- | | ``` [[noreturn]] void rethrow_nested() const; ``` | | (since C++11) | Rethrows the stored exception. If there is no stored exceptions (i.e. `[nested\_ptr()](nested_ptr "cpp/error/nested exception/nested ptr")` returns null pointer), then `[std::terminate](../terminate "cpp/error/terminate")` is called. ### Parameters (none). ### Return value (none). cpp std::nested_exception::operator= std::nested\_exception::operator= ================================= | | | | | --- | --- | --- | | ``` nested_exception& operator=( const nested_exception& other ) noexcept = default; ``` | | (since C++11) | Replaces the stored exception with the one held in `other`. ### Parameters | | | | | --- | --- | --- | | other | - | nested exception to replace the contents with | ### Return value `*this`. cpp std::system_error::operator= std::system\_error::operator= ============================= | | | | | --- | --- | --- | | ``` system_error& operator=( const system_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::system_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another `system_error` object to assign with | ### Return value `*this`. ### Example cpp std::system_error::system_error std::system\_error::system\_error ================================= | | | | | --- | --- | --- | | ``` system_error( std::error_code ec ); ``` | (1) | (since C++11) | | ``` system_error( std::error_code ec, const std::string& what_arg ); ``` | (2) | (since C++11) | | ``` system_error( std::error_code ec, const char* what_arg ); ``` | (2) | (since C++11) | | ``` system_error( int ev, const std::error_category& ecat ); ``` | (3) | (since C++11) | | ``` system_error( int ev, const std::error_category& ecat, const std::string& what_arg ); ``` | (4) | (since C++11) | | ``` system_error( int ev, const std::error_category& ecat, const char* what_arg ); ``` | (4) | (since C++11) | | ``` system_error( const system_error& other ) noexcept; ``` | (5) | (since C++11) | Constructs new system error object. 1) Constructs with error code `ec` 2) Constructs with error code `ec` and explanation string `what_arg`. The string returned by `[what()](what "cpp/error/system error/what")` is guaranteed to contain `what_arg` as a substring. 3) Constructs with underlying error code `ev` and associated error category `ecat`. 4) Constructs with underlying error code `ev`, associated error category `ecat` and explanatory string `what_arg`. The string returned by `[what()](what "cpp/error/system error/what")` is guaranteed to contain `what_arg` as a substring (assuming that it doesn't contain an embedded null character ). 5) Copy constructor. Initializes the contents with those of `other`. If `*this` and `other` both have dynamic type `std::system_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | ec | - | error code | | ev | - | underlying error code in the enumeration associated with `ecat` | | ecat | - | the category of error | | what\_arg | - | explanatory string | | other | - | another `system_error` to copy | ### Example Demonstrates how to create a system\_error exception from an `errno` value. ``` #include <iostream> #include <system_error> int main() { try { throw std::system_error(EDOM, std::generic_category(), "hello world"); } catch (const std::system_error& ex) { std::cout << ex.code() << '\n'; std::cout << ex.code().message() << '\n'; std::cout << ex.what() << '\n'; } } ``` Possible output: ``` generic:33 Numerical argument out of domain hello world: Numerical argument out of domain ``` cpp std::system_error::code std::system\_error::code ======================== | | | | | --- | --- | --- | | ``` const std::error_code& code() const noexcept; ``` | | (since C++11) | Returns the stored error code. ### Parameters (none). ### Return value The stored error code. ### See also | | | | --- | --- | | [what](what "cpp/error/system error/what") [virtual] | returns an explanatory string (virtual public member function) | cpp std::system_error::what std::system\_error::what ======================== | | | | | --- | --- | --- | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. ### See also | | | | --- | --- | | [code](code "cpp/error/system error/code") | returns error code (public member function) | cpp std::error_category::message std::error\_category::message ============================= | | | | | --- | --- | --- | | ``` virtual std::string message( int condition ) const = 0; ``` | | (since C++11) | Returns a string describing the given error condition for the error category represented by `*this`. ### Parameters | | | | | --- | --- | --- | | condition | - | specifies the error condition to describe | ### Return value A string describing the given error condition. ### Exceptions May throw implementation-defined exceptions. cpp std::error_category::error_category std::error\_category::error\_category ===================================== | | | | | --- | --- | --- | | ``` constexpr error_category() noexcept; ``` | (1) | (since C++11) | | ``` error_category( const error_category& ) = delete; ``` | (2) | (since C++11) | 1) Constructs the error category object. 2) Copy constructor is deleted. `error_category` is neither [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") nor [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). ### Parameters (none). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2145](https://cplusplus.github.io/LWG/issue2145) | C++11 | `error_category` was not constructible | default constructor added | cpp std::error_category::~error_category std::error\_category::~error\_category ====================================== | | | | | --- | --- | --- | | ``` virtual ~error_category(); ``` | | (since C++11) | Destroys the object. ### Parameters (none). cpp std::error_category::default_error_condition std::error\_category::default\_error\_condition =============================================== | | | | | --- | --- | --- | | ``` virtual std::error_condition default_error_condition( int code ) const noexcept; ``` | | (since C++11) | Returns the error condition for the given error code. Equivalent to `[std::error\_condition](http://en.cppreference.com/w/cpp/error/error_condition)(code, \*this)`. ### Parameters | | | | | --- | --- | --- | | code | - | error code for which to return error condition | ### Return value The error condition for the given error code. cpp std::error_category::equivalent std::error\_category::equivalent ================================ | | | | | --- | --- | --- | | ``` virtual bool equivalent( int code, const std::error_condition& condition ) const noexcept; ``` | (1) | (since C++11) | | ``` virtual bool equivalent( const std::error_code& code, int condition ) const noexcept; ``` | (2) | (since C++11) | Checks whether error code is equivalent to an error condition for the error category represented by `*this`. 1) Equivalent to `default_error_condition(code) == condition`. 2) Equivalent to `*this == code.category() && code.value() == condition`. ### Parameters | | | | | --- | --- | --- | | code | - | specifies the error code to compare | | condition | - | specifies the error condition to compare | ### Return value `true` if the error code is equivalent to the given error condition for the error category represented by `*this`, `false` otherwise. cpp std::error_category::name std::error\_category::name ========================== | | | | | --- | --- | --- | | ``` virtual const char* name() const noexcept = 0; ``` | | (since C++11) | Returns a pointer to a null-terminated byte string that specifies the name of the error category. ### Parameters (none). ### Return value Null-terminated byte string specifying the name of the error category. cpp std::error_category::operator==,!=,<,<=> std::error\_category::operator==,!=,<,<=> ========================================= | | | | | --- | --- | --- | | ``` bool operator==( const error_category& rhs ) const noexcept; ``` | (1) | (since C++11) | | ``` bool operator!=( const error_category& rhs ) const noexcept; ``` | (2) | (since C++11) (until C++20) | | ``` bool operator<( const error_category& rhs ) const noexcept; ``` | (3) | (since C++11) (until C++20) | | ``` std::strong_ordering operator<=>( const error_category& rhs ) const noexcept; ``` | (4) | (since C++20) | Compares to another error category. 1) Checks whether `*this` and `rhs` refer to the same object. 2) Checks whether `*this` and `rhs` do not refer to the same object. 3) Orders `*this` and `rhs` by the order of `this` and `&rhs`. Equivalent to `[std::less](http://en.cppreference.com/w/cpp/utility/functional/less)<const error_category\*>()(this, &rhs)`. 4) Orders `*this` and `rhs` by the order of `this` and `&rhs`. Equivalent to `[std::compare\_three\_way](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way)()(this, &rhs)`. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | rhs | - | specifies the `error_category` to compare | ### Return value 1) `true` if `*this` and `rhs` refer to the same object, `false` otherwise. 2) `true` if `*this` and `rhs` do not refer to the same object, `false` otherwise. 3) `true` if `*this` is less than `rhs` as defined by the order of `this` and `&rhs`. 4) `std::strong_order::less` if `*this` is less than `rhs` as defined by the order of `this` and `&rhs`, otherwise `std::strong_order::greater` if `rhs` is less than `*this` in the order, otherwise `std::strong_order::equal`. cpp std::error_condition::message std::error\_condition::message ============================== | | | | | --- | --- | --- | | ``` std::string message() const; ``` | | (since C++11) | Returns an explanatory message for the stored error code and error category. Effectively calls `category().message(value())`. ### Parameters (none). ### Return value An explanatory message for the stored error code and error category. ### Exceptions May throw implementation-defined exceptions. ### See also | | | | --- | --- | | [message](../error_category/message "cpp/error/error category/message") [virtual] | obtains the explanatory string (virtual public member function of `std::error_category`) | cpp std::error_condition::category std::error\_condition::category =============================== | | | | | --- | --- | --- | | ``` const error_category& category() const noexcept; ``` | | (since C++11) | Returns the stored error category. ### Parameters (none). ### Return value The stored error category. ### See also | | | | --- | --- | | [error\_category](../error_category "cpp/error/error category") (C++11) | base class for error categories (class) | cpp std::error_condition::operator bool std::error\_condition::operator bool ==================================== | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | (since C++11) | Checks whether the stored error code is not zero. ### Parameters (none). ### Return value `true` if `value != 0`, `false` otherwise. cpp std::error_condition::assign std::error\_condition::assign ============================= | | | | | --- | --- | --- | | ``` void assign( int val, const error_category& cat ) noexcept; ``` | | (since C++11) | Assigns contents to an error condition. Sets the error code to `val` and error category to `cat`. ### Parameters | | | | | --- | --- | --- | | val | - | error code | | cat | - | error category | ### Return value (none). cpp std::is_error_condition_enum std::is\_error\_condition\_enum =============================== | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` template< class T > struct is_error_condition_enum; ``` | | (since C++11) | If `T` is an error condition enum, this template provides the member constant `value` equal `true`. For any other type, `value` is `false`. This template may be specialized for a user-defined type to indicate that the type is eligible for `[std::error\_condition](../error_condition "cpp/error/error condition")` automatic conversions. The following class of the standard library is an error condition enum: `[std::errc](../errc "cpp/error/errc")`. ### Helper variable template | | | | | --- | --- | --- | | ``` template< class T > inline constexpr bool is_error_condition_enum_v = is_error_condition_enum<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant") ------------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `true` if `T` is an error condition enum, `false` otherwise (public static member constant) | ### Member functions | | | | --- | --- | | operator bool | converts the object to `bool`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `bool` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` | ### See also | | | | --- | --- | | [is\_error\_code\_enum](../error_code/is_error_code_enum "cpp/error/error code/is error code enum") (C++11) | identifies a class as an error\_code enumeration (class template) | cpp std::error_condition::operator= std::error\_condition::operator= ================================ | | | | | --- | --- | --- | | ``` error_condition& operator=( const error_condition& other ) noexcept; ``` | (1) | (since C++11) (implicitly declared) | | ``` template< class ErrorConditionEnum > error_condition& operator=( ErrorConditionEnum e ) noexcept; ``` | (2) | (since C++11) | Assigns contents to an error condition. 1) Copy assignment operator. Assigns the contents of `other`. 2) Assigns error condition for enum `e`. Effectively calls `make_error_condition` found by [argument-dependent lookup](../../language/adl "cpp/language/adl") for `e`. This overload participates in overload resolution only if `[std::is\_error\_condition\_enum](http://en.cppreference.com/w/cpp/error/error_condition/is_error_condition_enum)<ErrorConditionEnum>::value` is `true`. ### Parameters | | | | | --- | --- | --- | | other | - | another error condition to initialize with | | e | - | error condition enum | ### Notes The ADL-found `make_error_condition` is intended to be used in the original proposal [N2422](https://wg21.link/N2422), and used by all known implementations. However, the standard requires that only `std::make_error_condition` overloads are considered. This is [LWG issue 3629](https://cplusplus.github.io/LWG/issue3629). ### Return value `*this`.
programming_docs
cpp std::error_condition::clear std::error\_condition::clear ============================ | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Clears the state of the error condition. Sets the error code to `​0​` and error category to `[std::generic\_category](../generic_category "cpp/error/generic category")`. ### Parameters (none). ### Return value (none). cpp std::error_condition::value std::error\_condition::value ============================ | | | | | --- | --- | --- | | ``` int value() const noexcept; ``` | | (since C++11) | Returns the stored error code. ### Parameters (none). ### Return value The stored error code. cpp operator==,!=,<,<=>(std::error_condition) operator==,!=,<,<=>(std::error\_condition) ========================================== | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` bool operator==( const std::error_condition& lhs, const std::error_condition& rhs ) noexcept; ``` | (1) | (since C++11) | | ``` bool operator!=( const std::error_condition& lhs, const std::error_condition& rhs ) noexcept; ``` | (2) | (since C++11) (until C++20) | | ``` bool operator<( const std::error_condition& lhs, const std::error_condition& rhs ) noexcept; ``` | (3) | (since C++11) (until C++20) | | ``` std::strong_ordering operator<=>( const std::error_condition& lhs, const std::error_condition& rhs ) noexcept; ``` | (4) | (since C++20) | | ``` bool operator==( const std::error_code& code, const std::error_condition& cond ) noexcept; ``` | (5) | (since C++11) | | ``` bool operator==( const std::error_condition& cond, const std::error_code& code ) noexcept; ``` | (5) | (since C++11) (until C++20) | | ``` bool operator!=( const std::error_code& code, const std::error_condition& cond ) noexcept; ``` | (6) | (since C++11) (until C++20) | | ``` bool operator!=( const std::error_condition& cond, const std::error_code& code ) noexcept; ``` | (6) | (since C++11) (until C++20) | Compares two error conditions. 1) Checks whether `lhs` and `rhs` are equal. 2) Checks whether `lhs` and `rhs` are not equal. 3) Checks whether `lhs` is *less than* `rhs`. 4) Obtains three-way comparison result of `lhs` and `rhs`. 5) Checks whether `code` is a semantic match for `cond`. 6) Checks whether `code` is not a semantic match for `cond`. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs, cond | - | error conditions to compare | | code | - | the error code to compare | ### Return value 1) `true` if the error category and error value compare equal. 2) `true` if the error category or error value compare are not equal. 3) `true` if `lhs.category() < rhs.category()`. Otherwise, `true` if `lhs.category() == rhs.category() && lhs.value() < rhs.value()`. Otherwise, `false`. 4) `lhs.category() <=> rhs.category()` if it is not `std::strong_ordering::equal`. Otherwise, `lhs.value() <=> rhs.value()`. 5) `true` if either `code.category().equivalent(code.value(), cond)` or `cond.category().equivalent(code, cond.value())`. 6) `true` if neither `code.category().equivalent(code.value(), cond)` nor `cond.category().equivalent(code, cond.value())`. ### See also | | | | --- | --- | | [equivalent](../error_category/equivalent "cpp/error/error category/equivalent") [virtual] | compares `error_code` and `error_condition` for equivalence (virtual public member function of `std::error_category`) | | [operator==operator!=operator<operator<=>](../error_code/operator_cmp "cpp/error/error code/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares two `error_code`s (function) | cpp std::error_condition::error_condition std::error\_condition::error\_condition ======================================= | | | | | --- | --- | --- | | ``` error_condition() noexcept; ``` | (1) | (since C++11) | | ``` error_condition( const error_condition& other ) noexcept; ``` | (2) | (since C++11) (implicitly declared) | | ``` error_condition( int val, const error_category& cat ) noexcept; ``` | (3) | (since C++11) | | ``` template< class ErrorConditionEnum > error_condition( ErrorConditionEnum e ) noexcept; ``` | (4) | (since C++11) | Constructs new error condition. 1) Default constructor. Initializes the error condition with generic category and error code `​0​`. 2) Copy constructor. Initializes the error condition with the contents of `other`. 3) Initializes the error condition with error code `val` and error category `cat`. 4) Initializes the error condition with enum `e`. Effectively calls `make_error_condition` found by [argument-dependent lookup](../../language/adl "cpp/language/adl") for `e`. This overload participates in overload resolution only if `[std::is\_error\_condition\_enum](http://en.cppreference.com/w/cpp/error/error_condition/is_error_condition_enum)<ErrorConditionEnum>::value` is `true`. ### Parameters | | | | | --- | --- | --- | | other | - | another error condition to initialize with | | val | - | error code | | cat | - | error category | | e | - | error condition enum | ### Notes The ADL-found `make_error_condition` is intended to be used in the original proposal [N2422](https://wg21.link/N2422), and used by all known implementations. However, the standard requires that only `std::make_error_condition` overloads are considered. This is [LWG issue 3629](https://cplusplus.github.io/LWG/issue3629). ### See also | | | | --- | --- | | [make\_error\_condition(std::errc)](../errc/make_error_condition "cpp/error/errc/make error condition") (C++11) | constructs an `[std::errc](../errc "cpp/error/errc")` error condition (function) | | [make\_error\_condition(std::io\_errc)](../../io/io_errc/make_error_condition "cpp/io/io errc/make error condition") (C++11) | constructs an iostream error code (function) | | [make\_error\_condition(std::future\_errc)](../../thread/future_errc/make_error_condition "cpp/thread/future errc/make error condition") (C++11) | constructs a future error\_condition (function) | cpp std::error_code::message std::error\_code::message ========================= | | | | | --- | --- | --- | | ``` std::string message() const; ``` | | (since C++11) | Returns the message corresponding to the current error value and category. Equivalent to `category().message(value())`. ### Parameters (none). ### Return value The error message corresponding to the current error value and category. ### Exceptions May throw implementation-defined exceptions. cpp std::operator<<(std::error_code) std::operator<<(std::error\_code) ================================= | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` template< class CharT, class Traits > std::basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, const error_code& ec ); ``` | | (since C++11) | Performs stream output operation on error code `ec`. Equivalent to `os << ec.category().name() << ':' << ec.value()`. ### Parameters | | | | | --- | --- | --- | | os | - | output stream to insert data to | | ec | - | error code | ### Return value `os`. cpp std::error_code::default_error_condition std::error\_code::default\_error\_condition =========================================== | | | | | --- | --- | --- | | ``` std::error_condition default_error_condition() const noexcept; ``` | | (since C++11) | Returns the default error condition for the current error value. Equivalent to `category().default_error_condition(value())`. ### Parameters (none). ### Return value The default error condition for the current error value. cpp std::error_code::category std::error\_code::category ========================== | | | | | --- | --- | --- | | ``` const std::error_category& category() const noexcept; ``` | | (since C++11) | Returns the error category of the error value. ### Parameters (none). ### Return value The error category of the error value. ### See also | | | | --- | --- | | [value](value "cpp/error/error code/value") | obtains the value of the error\_code (public member function) | cpp std::error_code::operator bool std::error\_code::operator bool =============================== | | | | | --- | --- | --- | | ``` explicit operator bool() const noexcept; ``` | | (since C++11) | Checks if the error value is valid, i.e. non-zero. ### Parameters (none). ### Return value `false` if `value() == 0`, `true` otherwise. ### Notes Although this operator is often used as a convenient shorthand to check if any error was returned (as in `if (ec) { /* handle error */ }`, such use is not robust: some error codes, for example, HTTP status code 200, may indicate success as well. cpp std::error_code::assign std::error\_code::assign ======================== | | | | | --- | --- | --- | | ``` void assign( int ec, const error_category& ecat ) noexcept; ``` | | (since C++11) | Replaces the contents with error code `ec` and corresponding category `ecat`. ### Parameters | | | | | --- | --- | --- | | ec | - | platform-dependent error code enum to assign | | ecat | - | error category corresponding to `ec` | ### Return value (none). ### See also | | | | --- | --- | | [operator=](operator= "cpp/error/error code/operator=") | assigns another error code (public member function) | cpp std::is_error_code_enum std::is\_error\_code\_enum ========================== | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` template< class T > struct is_error_code_enum; ``` | | (since C++11) | If `T` is an error code enumeration, this template provides the member constant `value` equal `true`. For any other type, `value` is `false`. This template may be specialized for a user-defined type to indicate that the type is eligible for `[std::error\_code](../error_code "cpp/error/error code")` and `[std::error\_condition](../error_condition "cpp/error/error condition")` automatic conversions. The following classes of the standard library are an error code enum: * `[std::io\_errc](../../io/io_errc "cpp/io/io errc")` * `[std::future\_errc](../../thread/future_errc "cpp/thread/future errc")`. ### Helper variable template | | | | | --- | --- | --- | | ``` template< class T > inline constexpr bool is_error_code_enum_v = is_error_code_enum<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant") ------------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `true` if `T` is an error code enum, `false` otherwise (public static member constant) | ### Member functions | | | | --- | --- | | operator bool | converts the object to `bool`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `bool` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` | ### See also | | | | --- | --- | | [is\_error\_condition\_enum](../error_condition/is_error_condition_enum "cpp/error/error condition/is error condition enum") (C++11) | identifies an enumeration as an `[std::error\_condition](../error_condition "cpp/error/error condition")` (class template) | cpp std::error_code::operator= std::error\_code::operator= =========================== | | | | | --- | --- | --- | | ``` template< class ErrorCodeEnum > error_code& operator=( ErrorCodeEnum e ) noexcept; ``` | | (since C++11) | Replaces the error code and corresponding category with those representing error code enum `e`. Equivalent to `*this = make_error_code(e)`, where `make_error_code` is called unqualified to enable [argument-dependent lookup](../../language/adl "cpp/language/adl"). This overload participates in overload resolution only if `[std::is\_error\_code\_enum](http://en.cppreference.com/w/cpp/error/error_code/is_error_code_enum)<ErrorCodeEnum>::value` is `true`. ### Parameters | | | | | --- | --- | --- | | e | - | error code enum to construct | ### Return value `*this`. ### Notes Copy-assignment operator is defined implicitly. The ADL-found `make_error_code` is intended to be used in the original proposal [N2422](https://wg21.link/N2422), and used by all known implementations. However, the standard requires that only `std::make_error_code` overloads are considered. This is [LWG issue 3629](https://cplusplus.github.io/LWG/issue3629). ### See also | | | | --- | --- | | [assign](assign "cpp/error/error code/assign") | assigns another error code (public member function) | cpp std::error_code::clear std::error\_code::clear ======================= | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Replaces the error code and error category with default values. Equivalent to `\*this = error_code(0, [std::system\_category](http://en.cppreference.com/w/cpp/error/system_category)())`. ### Parameters (none). ### Return value (none). cpp std::error_code::value std::error\_code::value ======================= | | | | | --- | --- | --- | | ``` int value() const noexcept; ``` | | (since C++11) | Returns the platform dependent error value. ### Parameters (none). ### Return value The platform-dependent error value. ### See also | | | | --- | --- | | [category](category "cpp/error/error code/category") | obtains the error\_category for this error\_code (public member function) | cpp std::error_code::error_code std::error\_code::error\_code ============================= | | | | | --- | --- | --- | | ``` error_code() noexcept; ``` | (1) | (since C++11) | | ``` error_code( int ec, const error_category& ecat ) noexcept; ``` | (2) | (since C++11) | | ``` template< class ErrorCodeEnum > error_code( ErrorCodeEnum e ) noexcept; ``` | (3) | (since C++11) | Constructs new error code. 1) Constructs error code with default value. Equivalent to `error_code(0, [std::system\_category](http://en.cppreference.com/w/cpp/error/system_category)())`. 2) Constructs error code with `ec` as the platform-dependent error code and `ecat` as the corresponding [error category](../error_category "cpp/error/error category"). 3) Constructs error code from an error code enum `e`. Equivalent to `make_error_code(e)`, where `make_error_code` is found by [argument-dependent lookup](../../language/adl "cpp/language/adl"). This overload participates in overload resolution only if `[std::is\_error\_code\_enum](http://en.cppreference.com/w/cpp/error/error_code/is_error_code_enum)<ErrorCodeEnum>::value` is `true`. ### Parameters | | | | | --- | --- | --- | | ec | - | platform dependent error code to construct with | | ecat | - | error category corresponding to `ec` | | e | - | error code enum to construct with | ### Notes The ADL-found `make_error_code` is intended to be used in the original proposal [N2422](https://wg21.link/N2422), and used by all known implementations. However, the standard requires that only `std::make_error_code` overloads are considered. This is [LWG issue 3629](https://cplusplus.github.io/LWG/issue3629). ### See also | | | | --- | --- | | [make\_error\_code(std::errc)](../errc/make_error_code "cpp/error/errc/make error code") (C++11) | constructs an `[std::errc](../errc "cpp/error/errc")` error code (function) | | [make\_error\_code(std::io\_errc)](../../io/io_errc/make_error_code "cpp/io/io errc/make error code") (C++11) | constructs an iostream error code (function) | | [make\_error\_code(std::future\_errc)](../../thread/future_errc/make_error_code "cpp/thread/future errc/make error code") (C++11) | constructs a future error code (function) | cpp std::operator==,!=,<,<=>(std::error_code) std::operator==,!=,<,<=>(std::error\_code) ========================================== | Defined in header `[<system\_error>](../../header/system_error "cpp/header/system error")` | | | | --- | --- | --- | | ``` bool operator==( const std::error_code& lhs, const std::error_code& rhs ) noexcept; ``` | (1) | (since C++11) | | ``` bool operator!=( const std::error_code& lhs, const std::error_code& rhs ) noexcept; ``` | (2) | (since C++11) (until C++20) | | ``` bool operator<( const std::error_code& lhs, const std::error_code& rhs ) noexcept; ``` | (3) | (since C++11) (until C++20) | | ``` std::strong_ordering operator<=>( const std::error_code& lhs, const std::error_code& rhs ) noexcept; ``` | (4) | (since C++20) | Compares two error code objects. 1) Compares `lhs` and `rhs` for equality. 2) Compares `lhs` and `rhs` for equality. 3) Checks whether `lhs` is less than `rhs`. 4) Obtains three-way comparison result of `lhs` and `rhs`. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | error codes to compare | ### Return value 1) `true` if the error category and error value compare equal. 2) `true` if the error category or error value compare are not equal. 3) `true` if `lhs.category() < rhs.category()`. Otherwise, `true` if `lhs.category() == rhs.category() && lhs.value() < rhs.value()`. Otherwise, `false`. 4) `lhs.category() <=> rhs.category()` if it is not `std::strong_ordering::equal`. Otherwise, `lhs.value() <=> rhs.value()`. ### See also | | | | --- | --- | | [category](category "cpp/error/error code/category") | obtains the error\_category for this error\_code (public member function) | | [value](value "cpp/error/error code/value") | obtains the value of the error\_code (public member function) | | [operator==operator!=operator<operator<=>](../error_condition/operator_cmp "cpp/error/error condition/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares `error_condition`s and `error_code`s (function) | cpp std::exception::~exception std::exception::~exception ========================== | | | | | --- | --- | --- | | ``` virtual ~exception(); ``` | | | Destroys the exception object. cpp std::exception::exception std::exception::exception ========================= | | | | | --- | --- | --- | | | (1) | | | ``` exception() throw(); ``` | (until C++11) | | ``` exception() noexcept; ``` | (since C++11) | | | (2) | | | ``` exception( const exception& other ) throw(); ``` | (until C++11) | | ``` exception( const exception& other ) noexcept; ``` | (since C++11) | Constructs new exception object. 1) Default constructor. [`what()`](what "cpp/error/exception/what") returns an implementation-defined string. 2) Copy constructor. Initializes the contents with those of `other`. If `*this` and `other` both have dynamic type `std::exception` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. (since C++11) ### Parameters | | | | | --- | --- | --- | | other | - | another exception to assign the contents of | ### Notes Because copying `std::exception` is not permitted to throw exceptions, when derived classes (such as `[std::runtime\_error](../runtime_error "cpp/error/runtime error")`) have to manage a user-defined diagnostic message, it is typically implemented as a copy-on-write string. The Microsoft implementation includes non-standard constructors taking strings thus allowing instances to be thrown directly with a meaningful error message. The nearest standard equivalents are `[std::runtime\_error](../runtime_error "cpp/error/runtime error")` or `[std::logic\_error](../logic_error "cpp/error/logic error")`.
programming_docs
cpp std::exception::operator= std::exception::operator= ========================= | | | | | --- | --- | --- | | ``` exception& operator=( const exception& other ) throw(); ``` | | (until C++11) | | ``` exception& operator=( const exception& other ) noexcept; ``` | | (since C++11) | Copy assignment operator. Assigns the contents of `other`. | | | | --- | --- | | The effects of calling `[what()](what "cpp/error/exception/what")` after assignment are implementation-defined. | (until C++11) | | If `*this` and `other` both have dynamic type `std::exception` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | another exception to assign the contents of | cpp std::exception::what std::exception::what ==================== | | | | | --- | --- | --- | | ``` virtual const char* what() const throw(); ``` | | (until C++11) | | ``` virtual const char* what() const noexcept; ``` | | (since C++11) | Returns the explanatory string. ### Parameters (none). ### Return value Pointer to a null-terminated string with explanatory information. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function on the exception object is called. ### 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 108](https://cplusplus.github.io/LWG/issue108) | C++98 | it was unspecified when the returned pointer becomes invalid | specified | cpp Source file inclusion Source file inclusion ===================== Includes other source file into current source file at the line immediately after the directive. ### Syntax | | | | | --- | --- | --- | | `#include <` h-char-sequence `>` new-line | (1) | | | `#include "` q-char-sequence `"` new-line | (2) | | | `#include` pp-tokens new-line | (3) | | | `__has_include` `(` `"` q-char-sequence `"` `)``__has_include` `(` `<` h-char-sequence `>` `)` | (4) | (since C++17) | | `__has_include` `(` string-literal `)``__has_include` `(` `<` h-pp-tokens `>` `)` | (5) | (since C++17) | 1) Searches for a header identified uniquely by h-char-sequence and replaces the directive by the entire contents of the header. 2) Searches for a source file identified by q-char-sequence and replaces the directive by the entire contents of the source file. It may fallback to (1) and treat q-char-sequence as a header identifier. 3) If neither (1) and (2) is matched, pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (1) or (2) again. 4) Checks whether a header or source file is available for inclusion. 5) If (4) is not matched, h-pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (4) again. | | | | | --- | --- | --- | | new-line | - | The new-line character | | h-char-sequence | - | A sequence of one or more h-chars, where the appearance of any of the following is conditionally-supported with implementation-defined semantics: * the character `'` * the character `"` * the character `\` * the character sequence `//` * the character sequence `/*` | | h-char | - | Any member of the [source character set](../language/translation_phases#Phase_5 "cpp/language/translation phases") (until C++23)[translation character set](../language/charset#Translation_character_set "cpp/language/charset") (since C++23) except new-line and `>` | | q-char-sequence | - | A sequence of one or more q-chars, where the appearance of any of the following is conditionally-supported with implementation-defined semantics: * the character `'` * the character `\` * the character sequence `//` * the character sequence `/*` | | q-char | - | Any member of the [source character set](../language/translation_phases#Phase_5 "cpp/language/translation phases") (until C++23)[translation character set](../language/charset#Translation_character_set "cpp/language/charset") (since C++23) except new-line and `"` | | pp-tokens | - | A sequence of one or more [preprocessing tokens](../language/translation_phases#Phase_3 "cpp/language/translation phases") | | string-literal | - | A [string literal](../language/string_literal "cpp/language/string literal") | | h-pp-tokens | - | A sequence of one or more [preprocessing tokens](../language/translation_phases#Phase_3 "cpp/language/translation phases") except `>` | ### Explanation 1) Searches a sequence of implementation-defined places for a header identified uniquely by h-char-sequence, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. 2) Causes the replacement of that directive by the entire contents of the source file identified by q-char-sequence. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it reads syntax (1) with the identical contained sequence (including > characters, if any) from the original directive. 3) The preprocessing tokens after `include` in the directive are processed just as in normal text (i.e., each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens). If the directive resulting after all replacements does not match one of the two previous forms, the behavior is undefined. The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined into a single header name preprocessing token is implementation-defined. 4) The header or source file identified by h-char-sequence or q-char-sequence is searched for as if that preprocessing token sequence were the pp-tokens in syntax (3), except that no further macro expansion is performed. If such a directive would not satisfy the syntactic requirements of an `#include` directive, the program is ill-formed. The `__has_include` expression evaluates to 1 if the search for the source file succeeds, and to 0 if the search fails. 5) This form is considered only if syntax (4) does not match, in which case the preprocessing tokens are processed just as in normal text. | | | | --- | --- | | If the header identified by the header-name (i.e., `<` h-char-sequence `>` or `"` q-char-sequence `"`) denotes an importable header, it is implementation-defined whether the `#include` preprocessing directive is instead replaced by an [import directive](../language/modules#Importing_modules_and_headers "cpp/language/modules") of the form. `import` header-name `;` new-line. | (since C++20) | `__has_include` can be expanded in the expression of [`#if`](conditional "cpp/preprocessor/conditional") and [`#elif`](conditional "cpp/preprocessor/conditional"). It is treated as a defined macro by [`#ifdef`](conditional "cpp/preprocessor/conditional"), [`#ifndef`](conditional "cpp/preprocessor/conditional"), [`#elifdef`](conditional "cpp/preprocessor/conditional"), [`#elifndef`](conditional "cpp/preprocessor/conditional") (since C++23) and [`defined`](conditional "cpp/preprocessor/conditional") but cannot be used anywhere else. ### Notes Typical implementations search only standard include directories for syntax (1). The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options. The intent of syntax (2) is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides then falls back to (1). When a file is included, it is processed by [translation phases](../language/translation_phases "cpp/language/translation phases") 1-4, which may include, recursively, expansion of the nested `#include` directives, up to an implementation-defined nesting limit. To avoid repeated inclusion of the same file and endless recursion when a file includes itself, perhaps transitively, *header guards* are commonly used: the entire header is wrapped in. ``` #ifndef FOO_H_INCLUDED /* any name uniquely mapped to file name */ #define FOO_H_INCLUDED // contents of the file are here #endif ``` Many compilers also implement the non-standard [`pragma`](impl "cpp/preprocessor/impl") `#pragma once` with similar effects: it disables processing of a file if the same file (where file identity is determined in OS-specific way) has already been included. A sequence of characters that resembles an escape sequence in q-char-sequence or h-char-sequence might result in an error, be interpreted as the character corresponding to the escape sequence, or have a completely different meaning, depending on the implementation. A `__has_include` result of `1` only means that a header or source file with the specified name exists. It does not mean that the header or source file, when included, would not cause an error or would contain anything useful. For example, on a C++ implementation that supports both C++14 and C++17 modes (and provides `__has_include` in its C++14 mode as a conforming extension), `__has_include(<optional>)` may be `1` in C++14 mode, but actually `#include <optional>` may cause an error. ### Example ``` #if __has_include(<optional>) # include <optional> # define has_optional 1 template<class T> using optional_t = std::optional<T>; #elif __has_include(<experimental/optional>) # include <experimental/optional> # define has_optional -1 template<class T> using optional_t = std::experimental::optional<T>; #else # define has_optional 0 # include <utility> template<class V> class optional_t { V v_{}; bool has_{false}; public: optional_t() = default; optional_t(V&& v) : v_(v), has_{true} {} V value_or(V&& alt) const& { return has_ ? v_ : alt; } /*...*/ }; #endif #include <iostream> int main() { if (has_optional > 0) std::cout << "<optional> is present\n"; else if (has_optional < 0) std::cout << "<experimental/optional> is present\n"; else std::cout << "<optional> is not present\n"; optional_t<int> op; std::cout << "op = " << op.value_or(-1) << '\n'; op = 42; std::cout << "op = " << op.value_or(-1) << '\n'; } ``` Output: ``` <optional> is present op = -1 op = 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 | | --- | --- | --- | --- | | [CWG 787](https://cplusplus.github.io/CWG/issues/787.html) | C++98 | the behavior is undefined if an escape sequence isresembled in q-char-sequence or h-char-sequence | it is conditionally-supported | ### See also | | | --- | | [A list of C++ Standard Library header files](../index "cpp/header") | | [C documentation](https://en.cppreference.com/w/c/preprocessor/include "c/preprocessor/include") for Source file inclusion | cpp Replacing text macros Replacing text macros ===================== The preprocessor supports text macro replacement. Function-like text macro replacement is also supported. ### Syntax | | | | | --- | --- | --- | | `#define` identifier replacement-list(optional) | (1) | | | `#define` identifier`(` parameters `)` replacement-list(optional) | (2) | | | `#define` identifier`(` parameters`, ... )` replacement-list(optional) | (3) | (since C++11) | | `#define` identifier`( ... )` replacement-list(optional) | (4) | (since C++11) | | `#undef` identifier | (5) | | ### Explanation #### `#define` directives The `#define` directives define the identifier as macro, that is instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed unless the definitions are identical. ##### Object-like macros Object-like macros replace every occurrence of defined identifier with replacement-list. Version (1) of the `#define` directive behaves exactly like that. ##### Function-like macros Function-like macros replace each occurrence of defined identifier with replacement-list, additionally taking a number of arguments, which then replace corresponding occurrences of any of the parameters in the replacement-list. The syntax of a function-like macro invocation is similar to the syntax of a function call: each instance of the macro name followed by a `(` as the next preprocessing token introduces the sequence of tokens that is replaced by the replacement-list. The sequence is terminated by the matching `)` token, skipping intervening matched pairs of left and right parentheses. For version (2), the number of arguments must be the same as the number of parameters in macro definition. For versions (3,4), the number of arguments must not be less than the number of parameters (not (since C++20) counting `...`). Otherwise the program is ill-formed. If the identifier is not in functional-notation, i.e. does not have parentheses after itself, it is not replaced at all. Version (2) of the `#define` directive defines a simple function-like macro. Version (3) of the `#define` directive defines a function-like macro with variable number of arguments. The additional arguments (called *variable arguments*) can be accessed using `__VA_ARGS__` identifier, which is then replaced with arguments, supplied with the identifier to be replaced. Version (4) of the `#define` directive defines a function-like macro with variable number of arguments, but no regular arguments. The arguments (called *variable arguments*) can be accessed only with `__VA_ARGS__` identifier, which is then replaced with arguments, supplied with identifier to be replaced. | | | | --- | --- | | For versions (3,4), replacement-list may contain the token sequence `__VA_OPT__ (` content `)`, which is replaced by content if `__VA_ARGS__` is non-empty, and expands to nothing otherwise. ``` #define F(...) f(0 __VA_OPT__(,) __VA_ARGS__) F(a, b, c) // replaced by f(0, a, b, c) F() // replaced by f(0) #define G(X, ...) f(0, X __VA_OPT__(,) __VA_ARGS__) G(a, b, c) // replaced by f(0, a, b, c) G(a, ) // replaced by f(0, a) G(a) // replaced by f(0, a) #define SDEF(sname, ...) S sname __VA_OPT__(= { __VA_ARGS__ }) SDEF(foo); // replaced by S foo; SDEF(bar, 1, 2); // replaced by S bar = { 1, 2 }; ``` | (since C++20) | Note: if an argument of a function-like macro includes commas that are not protected by matched pairs of left and right parentheses (most commonly found in template argument lists, as in `[assert](http://en.cppreference.com/w/cpp/error/assert)([std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<int, int>);` or `BOOST_FOREACH([std::pair](http://en.cppreference.com/w/cpp/utility/pair)<int,int> p, m)`), the comma is interpreted as macro argument separator, causing a compilation failure due to argument count mismatch. #### Reserved macro names A translation unit that includes a standard library header may not `#define` or `#undef` names declared in any standard library header. A translation unit that uses any part of the standard library may not `#define` or `#undef` names lexically identical to: * [keywords](../keyword "cpp/keyword") | | | | --- | --- | | * [identifiers with special meaning](../keyword "cpp/keyword") * [any standard attribute token](../language/attributes#Standard_attributes "cpp/language/attributes") | (since C++11) | | | | | --- | --- | | except that `likely` and `unlikely` may be defined as function-like macros. | (since C++20) | Otherwise, the behavior is undefined. #### `#` and `##` operators In function-like macros, a `#` operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. In addition, the preprocessor adds backslashes to escape the quotes surrounding embedded string literals, if any, and doubles the backslashes within the string as necessary. All leading and trailing whitespace is removed, and any sequence of whitespace in the middle of the text (but not inside embedded string literals) is collapsed to a single space. This operation is called "stringification". If the result of stringification is not a valid string literal, the behavior is undefined. | | | | --- | --- | | When `#` appears before `__VA_ARGS__`, the entire expanded `__VA_ARGS__` is enclosed in quotes: ``` #define showlist(...) puts(#__VA_ARGS__) showlist(); // expands to puts("") showlist(1, "x", int); // expands to puts("1, \"x\", int") ``` | (since C++11) | A `##` operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers (which are not macro-expanded first) and then concatenates the result. This operation is called "concatenation" or "token pasting". Only tokens that form a valid token together may be pasted: identifiers that form a longer identifier, digits that form a number, or operators `+` and `=` that form a `+=`. A comment cannot be created by pasting `/` and `*` because comments are removed from text before macro substitution is considered. If the result begins with a sequence matching the syntax of [universal character name](../language/escape "cpp/language/escape"), the behavior is undefined. This determination does not consider the replacement of universal character names in [translation phase 3](../language/translation_phases#Phase_3 "cpp/language/translation phases"). (since C++23) If the result of concatenation is not a valid token, the behavior is undefined. Note: some compilers offer an extension that allows `##` to appear after a comma and before `__VA_ARGS__`, in which case the `##` does nothing when the variable arguments are present, but removes the comma when the variable arguments are not present: this makes it possible to define macros such as `fprintf (stderr, format, ##__VA_ARGS__)`. This can also be achieved in a standard manner using `__VA_OPT__`, such as `fprintf (stderr, format __VA_OPT__(, ) __VA_ARGS__)`. (since C++20). #### `#undef` directive The `#undef` directive undefines the identifier, that is cancels previous definition of the identifier by `#define` directive. If the identifier does not have associated macro, the directive is ignored. ### Predefined macros The following macro names are predefined in every translation unit. | | | | --- | --- | | \_\_cplusplus | denotes the version of C++ standard that is being used, expands to value * `199711L`(until C++11), * `201103L`(C++11), * `201402L`(C++14), * `201703L`(C++17), or * `202002L`(C++20) (macro constant) | | \_\_STDC\_HOSTED\_\_ (C++11) | expands to the integer constant `1` if the implementation is hosted (runs under an OS), `​0​` if freestanding (runs without an OS) (macro constant) | | \_\_FILE\_\_ | expands to the name of the current file, as a character string literal, can be changed by the [`#line`](line "cpp/preprocessor/line") directive (macro constant) | | \_\_LINE\_\_ | expands to the source file line number, an integer constant, can be changed by the [`#line`](line "cpp/preprocessor/line") directive (macro constant) | | \_\_DATE\_\_ | expands to the date of translation, a character string literal of the form `"Mmm dd yyyy"`. The first character of `"dd"` is a space if the day of the month is less than 10. The name of the month is as if generated by `[std::asctime](http://en.cppreference.com/w/cpp/chrono/c/asctime)()` (macro constant) | | \_\_TIME\_\_ | expands to the time of translation, a character string literal of the form `"hh:mm:ss"` (macro constant) | | \_\_STDCPP\_DEFAULT\_NEW\_ALIGNMENT\_\_ (C++17) | expands to an `[std::size\_t](../types/size_t "cpp/types/size t")` literal whose value is the alignment guaranteed by a call to alignment-unaware [operator new](../memory/new/operator_new "cpp/memory/new/operator new") (larger alignments will be passed to alignment-aware overload, such as `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), [std::align\_val\_t](http://en.cppreference.com/w/cpp/memory/new/align_val_t))` (macro constant) | The following additional macro names may be predefined by the implementations. | | | | --- | --- | | \_\_STDC\_\_ | implementation-defined value, if present, typically used to indicate C conformance (macro constant) | | \_\_STDC\_VERSION\_\_ (C++11) | implementation-defined value, if present (macro constant) | | \_\_STDC\_ISO\_10646\_\_ (C++11) | expands to an integer constant of the form `yyyymmL`, if `wchar_t` uses Unicode, the date indicates the latest revision of Unicode supported (macro constant) | | \_\_STDC\_MB\_MIGHT\_NEQ\_WC\_\_ (C++11) | expands to `1` if `'x' == L'x'` might be false for a member of the basic character set, such as on EBCDIC-based systems that use Unicode for `wchar_t` (macro constant) | | \_\_STDCPP\_THREADS\_\_ (C++11) | expands to `1` if the program can have more than one thread of execution (macro constant) | | | | | --- | --- | | \_\_STDCPP\_STRICT\_POINTER\_SAFETY\_\_ (C++11)(removed in C++23) | expands to `1` if the implementation has strict `[std::pointer\_safety](../memory/gc/pointer_safety "cpp/memory/gc/pointer safety")` (macro constant) | The values of these macros (except for `__FILE__` and `__LINE__`) remain constant throughout the translation unit. Attempts to redefine or undefine these macros result in undefined behavior. | | | | --- | --- | | Note: in the scope of every function body, there is a special function-local predefined variable named `__func__`, defined as a static character array holding the name of the function in implementation-defined format. It is not a preprocessor macro, but it is used together with `__FILE__` and `__LINE__`, e.g. by `[assert](../error/assert "cpp/error/assert")`. | (since C++11) | | | | | --- | --- | | Language feature-testing macros The standard defines a set of preprocessor macros corresponding to C++ language features introduced in C++11 or later. They are intended as a simple and portable way to detect the presence of said features. See [Feature testing](../feature_test "cpp/feature test") for details. | (since C++20) | ### Example ``` #include <iostream> // Make function factory and use it #define FUNCTION(name, a) int fun_##name() { return a;} FUNCTION(abcd, 12) FUNCTION(fff, 2) FUNCTION(qqq, 23) #undef FUNCTION #define FUNCTION 34 #define OUTPUT(a) std::cout << "output: " #a << '\n' // Using a macro in the definition of a later macro #define WORD "Hello " #define OUTER(...) WORD #__VA_ARGS__ int main() { std::cout << "abcd: " << fun_abcd() << '\n'; std::cout << "fff: " << fun_fff() << '\n'; std::cout << "qqq: " << fun_qqq() << '\n'; std::cout << FUNCTION << '\n'; OUTPUT(million); //note the lack of quotes std::cout << OUTER(World) << '\n'; std::cout << OUTER(WORD World) << '\n'; } ``` Output: ``` abcd: 12 fff: 2 qqq: 23 34 output: million Hello World Hello WORD World ``` ### See also * [Macro Symbol Index](../symbol_index/macro "cpp/symbol index/macro") | | | --- | | [C documentation](https://en.cppreference.com/w/c/preprocessor/replace "c/preprocessor/replace") for Replacing text macros |
programming_docs
cpp Implementation defined behavior control Implementation defined behavior control ======================================= Implementation defined behavior is controlled by `#pragma` directive. ### Syntax | | | | | --- | --- | --- | | `#pragma` pragma-params | (1) | | | `_Pragma(` string-literal `)` | (2) | (since C++11) | 1) Behaves in implementation-defined manner 2) Removes the `L` prefix (if any), the outer quotes, and leading/trailing whitespace from string-literal, replaces each `\"` with `"` and each `\\` with `\`, then tokenizes the result (as in [translation phase 3](../language/translation_phases#Phase_3 "cpp/language/translation phases")), and then uses the result as if the input to `#pragma` in (1) ### Explanation Pragma directive controls implementation-specific behavior of the compiler, such as disabling compiler warnings or changing alignment requirements. Any pragma that is not recognized is ignored. ### Non-standard pragmas The ISO C++ language standard does not require the compilers to support any pragmas. However, several non-standard pragmas are supported by multiple implementations: #### #pragma STDC ISO C language standard requires that C compilers support the following three pragmas, and some C++ compiler vendors support them, to varying degrees, in their C++ frontends: | | | | | --- | --- | --- | | `#pragma STDC FENV_ACCESS` arg | (1) | | | `#pragma STDC FP_CONTRACT` arg | (2) | | | `#pragma STDC CX_LIMITED_RANGE` arg | (3) | | where arg is either `ON`, `OFF`, or `DEFAULT`. 1) If set to `ON`, informs the compiler that the program will access or modify [floating-point environment](../numeric/fenv "cpp/numeric/fenv"), which means that optimizations that could subvert flag tests and mode changes (e.g., global common subexpression elimination, code motion, and constant folding) are prohibited. The default value is implementation-defined, usually `OFF`. 2) Allows *contracting* of floating-point expressions, that is optimizations that omit rounding errors and floating-point exceptions that would be observed if the expression was evaluated exactly as written. For example, allows the implementation of `(x*y) + z` with a single fused multiply-add CPU instruction. The default value is implementation-defined, usually `ON`. 3) Informs the compiler that multiplication, division, and absolute value of complex numbers may use simplified mathematical formulas (x+iy)×(u+iv) = (xu-yv)+i(yu+xv), (x+iy)/(u+iv) = [(xu+yv)+i(yu-xv)]/(u2 +v2 ), and |x+iy| = √x2 +y2 , despite the possibility of intermediate overflow. In other words, the programmer guarantees that the range of the values that will be passed to those function is limited. The default value is `OFF`. The behavior of the program is undefined if any of the three pragmas above appear in any context other than outside all external declarations or preceding all explicit declarations and statements inside a compound statement. Note: compilers that do not support these pragmas may provide equivalent compile-time options, such as gcc's `-fcx-limited-range` and `-ffp-contract`. #### #pragma once `#pragma once` is a non-standard pragma that is supported by the [vast majority of modern compilers](https://en.wikipedia.org/wiki/Pragma_once#Portability "enwiki:Pragma once"). If it appears in a header file, it indicates that it is only to be parsed once, even if it is (directly or indirectly) included multiple times in the same source file. Standard approach to preventing multiple inclusion of the same header is by using [include guards](https://en.wikipedia.org/wiki/Include_guard "enwiki:Include guard"): ``` #ifndef LIBRARY_FILENAME_H #define LIBRARY_FILENAME_H // contents of the header #endif /* LIBRARY_FILENAME_H */ ``` So that all but the first inclusion of the header in any translation unit are excluded from compilation. All modern compilers record the fact that a header file uses an include guard and do not re-parse the file if it is encountered again, as long as the guard is still defined. (see e.g. [gcc](https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html)). With `#pragma once`, the same header appears as. ``` #pragma once // contents of the header ``` Unlike header guards, this pragma makes it impossible to erroneously use the same macro name in more than one file. On the other hand, since with `#pragma once` files are excluded based on their filesystem-level identity, this can't protect against including a header twice if it exists in more than one location in a project. #### #pragma pack This family of pragmas control the maximum alignment for subsequently defined class and union members. | | | | | --- | --- | --- | | `#pragma pack(arg)` | (1) | | | `#pragma pack()` | (2) | | | `#pragma pack(push)` | (3) | | | `#pragma pack(push, arg)` | (4) | | | `#pragma pack(pop)` | (5) | | where arg is a small power of two and specifies the new alignment in bytes. 1) Sets the current alignment to value arg. 2) Sets the current alignment to the default value (specified by a command-line option). 3) Pushes the value of the current alignment on an internal stack. 4) Pushes the value of the current alignment on the internal stack and then sets the current alignment to value arg. 5) Pops the top entry from the internal stack and then sets (restores) the current alignment to that value. `#pragma pack` may decrease the alignment of a class, however, it cannot make a class overaligned. See also specific details for [GCC](https://gcc.gnu.org/onlinedocs/gcc/Structure-Layout-Pragmas.html) and [MSVC](https://docs.microsoft.com/en-us/cpp/preprocessor/pack). ### References * C++98 standard (ISO/IEC 14882:1998): + 16.6 Pragma directive [cpp.pragma] * C++11 standard (ISO/IEC 14882:2011): + 16.6 Pragma directive [cpp.pragma] * C++14 standard (ISO/IEC 14882:2014): + 16.6 Pragma directive [cpp.pragma] * C++17 standard (ISO/IEC 14882:2017): + 19.6 Pragma directive [cpp.pragma] * C++20 standard (ISO/IEC 14882:2020): + 15.9 Pragma directive [cpp.pragma] * C++23 standard (ISO/IEC 14882:2023): + 15.9 Pragma directive [cpp.pragma] ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/preprocessor/impl "c/preprocessor/impl") for Implementation defined behavior control | ### External links * [C++ pragmas in Visual Studio](https://docs.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword) * [Pragmas](https://gcc.gnu.org/onlinedocs/gcc/Pragmas.html) accepted by GCC * [Individual pragma descriptions](https://www.ibm.com/support/knowledgecenter/en/SSGH3R_16.1.0/com.ibm.xlcpp161.aix.doc/compiler_ref/pragma_descriptions.html) and [Standard pragmas](https://www.ibm.com/support/knowledgecenter/en/SSGH3R_16.1.0/com.ibm.xlcpp161.aix.doc/language_ref/std_pragmas.html) in IBM AIX XL C 16.1 * [Appendix B. Pragmas](http://download.oracle.com/docs/cd/E19422-01/819-3690/Pragmas_App.html#73499) in Sun Studio 11 C++ User's Guide * [Intel C++ compiler pragmas](https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/pragmas.html) * [Release nodes (includes pragmas)](http://h20565.www2.hpe.com/hpsc/doc/public/display?sp4ts.oid=4268164&docLocale=en_US&docId=emr_na-c02653979) for HP aCC A.06.25 cpp Diagnostic directives Diagnostic directives ===================== Shows the given error message and renders the program ill-formed, or given warning message without affect the validity of the program (since C++23). ### Syntax | | | | | --- | --- | --- | | `#error` diagnostic-message | (1) | | | `#warning` diagnostic-message | (2) | (since C++23) | ### Explanation 1) After encountering the `#error` directive, an implementation displays the message diagnostic-message and renders the program ill-formed (the compilation stops). 2) Same as (1), except that the validity of the program is not affected and the compilation continues. diagnostic-message can consist of several words not necessarily in quotes. ### Notes Before its standardization in C++23, `#warning` has been provided by many compilers in all modes as a conforming extension. ### Example ``` #if __STDC_HOSTED__ != 1 # error "Not a hosted implementation" #endif #if __cplusplus >= 202302L # warning "Using #warning as a standard feature" #endif #include <iostream> int main() { std::cout << "The implementation used is hosted"; } ``` Possible output: ``` The implementation used is hosted ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 15.8 Error directive [cpp.error] * C++17 standard (ISO/IEC 14882:2017): + 19.5 Error directive [cpp.error] * C++14 standard (ISO/IEC 14882:2014): + 16.5 Error directive [cpp.error] * C++11 standard (ISO/IEC 14882:2011): + 16.5 Error directive [cpp.error] * C++03 standard (ISO/IEC 14882:2003): + 16.5 Error directive [cpp.error] * C++98 standard (ISO/IEC 14882:1998): + 16.5 Error directive [cpp.error] ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/preprocessor/error "c/preprocessor/error") for Diagnostic directives | cpp Conditional inclusion Conditional inclusion ===================== The preprocessor supports conditional compilation of parts of source file. This behavior is controlled by `#if`, `#else`, `#elif`, `#ifdef`, `#ifndef`, `#elifdef`, `#elifndef` (since C++23), and `#endif` directives. ### Syntax | | | | | --- | --- | --- | | `#if` expression | | | | `#ifdef` identifier | | | | `#ifndef` identifier | | | | `#elif` expression | | | | `#elifdef` identifier | | (since C++23) | | `#elifndef` identifier | | (since C++23) | | `#else` | | | | `#endif` | | | ### Explanation The conditional preprocessing block starts with `#if`, `#ifdef` or `#ifndef` directive, then optionally includes any number of `#elif`, `#elifdef`, or `#elifndef` (since C++23) directives, then optionally includes at most one `#else` directive and is terminated with `#endif` directive. Any inner conditional preprocessing blocks are processed separately. Each of `#if`, `#ifdef`, `#ifndef`, `#elif`, `#elifdef`, `#elifndef` (since C++23), and `#else` directives control the code block until the first `#elif`, `#elifdef`, `#elifndef` (since C++23), `#else`, `#endif` directive not belonging to any inner conditional preprocessing blocks. `#if`, `#ifdef` and `#ifndef` directives test the specified condition (see below) and if it evaluates to true, compiles the controlled code block. In that case subsequent `#else`, `#elifdef`, `#elifndef`, (since C++23) and `#elif` directives are ignored. Otherwise, if the specified condition evaluates false, the controlled code block is skipped and the subsequent `#else`, `#elifdef`, `#elifndef`, (since C++23) or `#elif` directive (if any) is processed. If the subsequent directive is `#else`, the code block controlled by the `#else` directive is unconditionally compiled. Otherwise, the `#elif`, `#elifdef`, or `#elifndef` (since C++23) directive acts as if it was `#if` directive: checks for condition, compiles or skips the controlled code block based on the result, and in the latter case processes subsequent `#elif`, `#elifdef`, `#elifndef`, (since C++23) and `#else` directives. The conditional preprocessing block is terminated by `#endif` directive. ### Condition evaluation #### `#if, #elif` The expression is a [constant expression](../language/constant_expression "cpp/language/constant expression"). The expression may contain: * unary operators in form `defined` identifier or `defined (`identifier`)`. The result is `1` if the identifier was [defined as a macro name](replace "cpp/preprocessor/replace"), otherwise the result is `​0​`. * (since C++17) [`__has_include`](include "cpp/preprocessor/include") expressions, which detects whether a header or source file exists. * (since C++20) [`__has_cpp_attribute`](../feature_test#Attributes "cpp/feature test") expressions, which detects whether a given attribute token is supported and its supported version. After all macro expansion and evaluation of `defined` , `__has_include` (since C++17), and `__has_cpp_attribute` (since C++20) expressions, any identifier which is not a [boolean literal](../language/bool_literal "cpp/language/bool literal") is replaced with the number `​0​` (this includes identifiers that are lexically keywords, but not alternative tokens like `and`). Then the expression is evaluated as an [integral constant expression](../language/constant_expression#Integral_constant_expression "cpp/language/constant expression"). If the expression evaluates to nonzero value, the controlled code block is included and skipped otherwise. Note: Until the resolution of [CWG issue 1955](https://cplusplus.github.io/CWG/issues/1955.html), `#if cond1` ... `#elif cond2` is different from `#if cond1` ... `#else` followed by `#if cond2` because if `cond1` is true, the second `#if` is skipped and `cond2` does not need to be well-formed, while `#elif`'s `cond2` must be a valid expression. As of CWG 1955, `#elif` that leads the skipped code block is also skipped. #### Combined directives Checks if the identifier was [defined as a macro name](replace "cpp/preprocessor/replace"). `#ifdef` identifier is essentially equivalent to `#if defined` identifier. `#ifndef` identifier is essentially equivalent to `#if !defined` identifier. | | | | --- | --- | | `#elifdef` identifier is essentially equivalent to `#elif defined` identifier. `#elifndef` identifier is essentially equivalent to `#elif !defined` identifier. | (since C++23) | ### Notes While `#elifdef` and `#elifndef` directives target C++23, implementations are encouraged to backport them to the older language modes as conforming extensions. ### Example ``` #define ABCD 2 #include <iostream> int main() { #ifdef ABCD std::cout << "1: yes\n"; #else std::cout << "1: no\n"; #endif #ifndef ABCD std::cout << "2: no1\n"; #elif ABCD == 2 std::cout << "2: yes\n"; #else std::cout << "2: no2\n"; #endif #if !defined(DCBA) && (ABCD < 2*4-3) std::cout << "3: yes\n"; #endif // Note that if a compiler does not support C++23's #elifdef/#elifndef // directives then the "unexpected" block (see below) will be selected. #ifdef CPU std::cout << "4: no1\n"; #elifdef GPU std::cout << "4: no2\n"; #elifndef RAM std::cout << "4: yes\n"; // expected block #else std::cout << "4: no!\n"; // unexpectedly selects this block by skipping // unknown directives and "jumping" directly // from "#ifdef CPU" to this "#else" block #endif // To fix the problem above we may conditionally define the // macro ELIFDEF_SUPPORTED only if the C++23 directives // #elifdef/#elifndef are supported. #if 0 #elifndef UNDEFINED_MACRO #define ELIFDEF_SUPPORTED #else #endif #ifdef ELIFDEF_SUPPORTED #ifdef CPU std::cout << "4: no1\n"; #elifdef GPU std::cout << "4: no2\n"; #elifndef RAM std::cout << "4: yes\n"; // expected block #else std::cout << "4: no3\n"; #endif #else // when #elifdef unsupported use old verbose `#elif defined` #ifdef CPU std::cout << "4: no1\n"; #elif defined GPU std::cout << "4: no2\n"; #elif !defined RAM std::cout << "4: yes\n"; // expected block #else std::cout << "4: no3\n"; #endif #endif } ``` Possible output: ``` 1: yes 2: yes 3: yes 4: no! 4: yes ``` ### 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 1955](https://cplusplus.github.io/CWG/issues/1955.html) | C++98 | failed `#elif`'s expression was required to be valid | failed `#elif` is skipped | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/preprocessor/conditional "c/preprocessor/conditional") for Conditional inclusion | cpp Filename and line information Filename and line information ============================= Changes the current file name and number in the preprocessor. ### Syntax | | | | | --- | --- | --- | | `#line` lineno | (1) | | | `#line` lineno `"`filename`"` | (2) | | ### Explanation 1) Changes the current preprocessor line number to lineno. Expansions of the macro `__LINE__` beyond this point will expand to lineno plus the number of actual source code lines encountered since. 2) Also changes the current preprocessor file name to filename. Expansions of the macro `__FILE__` from this point will produce filename. Any preprocessing tokens (macro constants or expressions) are permitted as arguments to `#line` as long as they expand to a valid decimal integer optionally following a valid character string. lineno must be a sequence of at least one decimal digit (the program is ill-formed, otherwise) and is always interpreted as decimal (even if it starts with `0`). If lineno is `0` or greater than `32767` (until C++11)`2147483647` (since C++11), the behavior is undefined. ### Notes This directive is used by some automatic code generation tools which produce C++ source files from a file written in another language. In that case, `#line` directives may be inserted in the generated C++ file referencing line numbers and the file name of the original (human-editable) source file. ### Example ``` #include <cassert> #define FNAME "test.cc" int main() { #line 777 FNAME assert(2+2 == 5); } ``` Output: ``` test: test.cc:777: int main(): Assertion `2+2 == 5' failed. ``` ### References * C++98 standard (ISO/IEC 14882:1998): + 16.4 Line control [cpp.line] * C++11 standard (ISO/IEC 14882:2011): + 16.4 Line control [cpp.line] * C++14 standard (ISO/IEC 14882:2014): + 16.4 Line control [cpp.line] * C++17 standard (ISO/IEC 14882:2017): + 19.4 Line control [cpp.line] * C++20 standard (ISO/IEC 14882:2020): + 15.7 Line control [cpp.line] * C++23 standard (ISO/IEC 14882:2023): + 15.7 Line control [cpp.line] ### See also | | | | --- | --- | | [source\_location](../utility/source_location "cpp/utility/source location") (C++20) | A class representing information about the source code, such as file names, line numbers, and function names (class) | | [C documentation](https://en.cppreference.com/w/c/preprocessor/line "c/preprocessor/line") for Filename and line information | cpp Standard library header <future> (C++11) Standard library header <future> (C++11) ======================================== This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [promise](../thread/promise "cpp/thread/promise") (C++11) | stores a value for asynchronous retrieval (class template) | | [packaged\_task](../thread/packaged_task "cpp/thread/packaged task") (C++11) | packages a function to store its return value for asynchronous retrieval (class template) | | [future](../thread/future "cpp/thread/future") (C++11) | waits for a value that is set asynchronously (class template) | | [shared\_future](../thread/shared_future "cpp/thread/shared future") (C++11) | waits for a value (possibly referenced by other futures) that is set asynchronously (class template) | | [launch](../thread/launch "cpp/thread/launch") (C++11) | specifies the launch policy for `[std::async](../thread/async "cpp/thread/async")` (enum) | | [future\_status](../thread/future_status "cpp/thread/future status") (C++11) | specifies the results of timed waits performed on `[std::future](../thread/future "cpp/thread/future")` and `[std::shared\_future](../thread/shared_future "cpp/thread/shared future")` (enum) | | [future\_error](../thread/future_error "cpp/thread/future error") (C++11) | reports an error related to futures or promises (class) | | [future\_errc](../thread/future_errc "cpp/thread/future errc") (C++11) | identifies the future error codes (enum) | | [std::uses\_allocator<std::promise>](../thread/promise/uses_allocator "cpp/thread/promise/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | [std::uses\_allocator<std::packaged\_task>](../thread/packaged_task/uses_allocator "cpp/thread/packaged task/uses allocator") (C++11) (until C++17) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | Functions | | [async](../thread/async "cpp/thread/async") (C++11) | runs a function asynchronously (potentially in a new thread) and returns a `[std::future](../thread/future "cpp/thread/future")` that will hold the result (function template) | | [future\_category](../thread/future_category "cpp/thread/future category") (C++11) | identifies the future error category (function) | | [std::swap(std::promise)](../thread/promise/swap2 "cpp/thread/promise/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::packaged\_task)](../thread/packaged_task/swap2 "cpp/thread/packaged task/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` namespace std { enum class future_errc { broken_promise = /* implementation-defined */, future_already_retrieved = /* implementation-defined */, promise_already_satisfied = /* implementation-defined */, no_state = /* implementation-defined */ }; enum class launch : /* unspecified */ { async = /* unspecified */, deferred = /* unspecified */, /* implementation-defined */ }; enum class future_status { ready, timeout, deferred }; template<> struct is_error_code_enum<future_errc> : public true_type { }; error_code make_error_code(future_errc e) noexcept; error_condition make_error_condition(future_errc e) noexcept; const error_category& future_category() noexcept; class future_error; template<class R> class promise; template<class R> class promise<R&>; template<> class promise<void>; template<class R> void swap(promise<R>& x, promise<R>& y) noexcept; template<class R, class Alloc> struct uses_allocator<promise<R>, Alloc>; template<class R> class future; template<class R> class future<R&>; template<> class future<void>; template<class R> class shared_future; template<class R> class shared_future<R&>; template<> class shared_future<void>; template<class> class packaged_task; // not defined template<class R, class... ArgTypes> class packaged_task<R(ArgTypes...)>; template<class R, class... ArgTypes> void swap(packaged_task<R(ArgTypes...)>&, packaged_task<R(ArgTypes...)>&) noexcept; template<class F, class... Args> [[nodiscard]] future<invoke_result_t<decay_t<F>, decay_t<Args>...>> async(F&& f, Args&&... args); template<class F, class... Args> [[nodiscard]] future<invoke_result_t<decay_t<F>, decay_t<Args>...>> async(launch policy, F&& f, Args&&... args); } ``` #### Class `[std::future\_error](../thread/future_error "cpp/thread/future error")` ``` namespace std { class future_error : public logic_error { public: explicit future_error(future_errc e); const error_code& code() const noexcept; const char* what() const noexcept; private: error_code ec_; // exposition only }; } ``` #### Class template `[std::promise](../thread/promise "cpp/thread/promise")` ``` namespace std { template<class R> class promise { public: promise(); template<class Allocator> promise(allocator_arg_t, const Allocator& a); promise(promise&& rhs) noexcept; promise(const promise&) = delete; ~promise(); // assignment promise& operator=(promise&& rhs) noexcept; promise& operator=(const promise&) = delete; void swap(promise& other) noexcept; // retrieving the result future<R> get_future(); // setting the result void set_value(/* see description */); void set_exception(exception_ptr p); // setting the result with deferred notification void set_value_at_thread_exit(/* see description */); void set_exception_at_thread_exit(exception_ptr p); }; template<class R> void swap(promise<R>& x, promise<R>& y) noexcept; template<class R, class Alloc> struct uses_allocator<promise<R>, Alloc>; } ``` #### Class template `[std::future](../thread/future "cpp/thread/future")` ``` namespace std { template<class R> class future { public: future() noexcept; future(future&&) noexcept; future(const future&) = delete; ~future(); future& operator=(const future&) = delete; future& operator=(future&&) noexcept; shared_future<R> share() noexcept; // retrieving the value /* see description */ get(); // functions to check state bool valid() const noexcept; void wait() const; template<class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template<class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; } ``` #### Class template `[std::shared\_future](../thread/shared_future "cpp/thread/shared future")` ``` namespace std { template<class R> class shared_future { public: shared_future() noexcept; shared_future(const shared_future& rhs) noexcept; shared_future(future<R>&&) noexcept; shared_future(shared_future&& rhs) noexcept; ~shared_future(); shared_future& operator=(const shared_future& rhs) noexcept; shared_future& operator=(shared_future&& rhs) noexcept; // retrieving the value /* see description */ get() const; // functions to check state bool valid() const noexcept; void wait() const; template<class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template<class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; } ``` #### Class template `[std::packaged\_task](../thread/packaged_task "cpp/thread/packaged task")` ``` namespace std { template<class> class packaged_task; // not defined template<class R, class... ArgTypes> class packaged_task<R(ArgTypes...)> { public: // construction and destruction packaged_task() noexcept; template<class F> explicit packaged_task(F&& f); ~packaged_task(); // no copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; // move support packaged_task(packaged_task&& rhs) noexcept; packaged_task& operator=(packaged_task&& rhs) noexcept; void swap(packaged_task& other) noexcept; bool valid() const noexcept; // result retrieval future<R> get_future(); // execution void operator()(ArgTypes... ); void make_ready_at_thread_exit(ArgTypes...); void reset(); }; template<class R, class... ArgTypes> packaged_task(R (*)(ArgTypes...)) -> packaged_task<R(ArgTypes...)>; template<class F> packaged_task(F) -> packaged_task</* see description */>; template<class R, class... ArgTypes> void swap(packaged_task<R(ArgTypes...)>& x, packaged_task<R(ArgTypes...)>& y) noexcept; } ```
programming_docs
cpp Standard library header <iomanip> Standard library header <iomanip> ================================= This header is part of the [Input/output](../io/manip "cpp/io/manip") library. | | | --- | | Functions | | [resetiosflags](../io/manip/resetiosflags "cpp/io/manip/resetiosflags") | clears the specified ios\_base flags (function) | | [setiosflags](../io/manip/setiosflags "cpp/io/manip/setiosflags") | sets the specified ios\_base flags (function) | | [setbase](../io/manip/setbase "cpp/io/manip/setbase") | changes the base used for integer I/O (function) | | [setfill](../io/manip/setfill "cpp/io/manip/setfill") | changes the fill character (function template) | | [setprecision](../io/manip/setprecision "cpp/io/manip/setprecision") | changes floating-point precision (function) | | [setw](../io/manip/setw "cpp/io/manip/setw") | changes the width of the next input/output field (function) | | [get\_money](../io/manip/get_money "cpp/io/manip/get money") (C++11) | parses a monetary value (function template) | | [put\_money](../io/manip/put_money "cpp/io/manip/put money") (C++11) | formats and outputs a monetary value (function template) | | [get\_time](../io/manip/get_time "cpp/io/manip/get time") (C++11) | parses a date/time value of specified format (function template) | | [put\_time](../io/manip/put_time "cpp/io/manip/put time") (C++11) | formats and outputs a date/time value according to the specified format (function template) | | [quoted](../io/manip/quoted "cpp/io/manip/quoted") (C++14) | inserts and extracts quoted strings with embedded spaces (function template) | ### Synopsis ``` namespace std { /*unspecified*/ resetiosflags(ios_base::fmtflags mask); /*unspecified*/ setiosflags (ios_base::fmtflags mask); /*unspecified*/ setbase(int base); template<class CharT> /*unspecified*/ setfill(CharT c); /*unspecified*/ setprecision(int n); /*unspecified*/ setw(int n); template<class MoneyT> /*unspecified*/ get_money(MoneyT& mon, bool intl = false); template<class MoneyT> /*unspecified*/ put_money(const MoneyT& mon, bool intl = false); template<class CharT> /*unspecified*/ get_time(struct tm* tmb, const CharT* fmt); template<class CharT> /*unspecified*/ put_time(const struct tm* tmb, const CharT* fmt); template<class CharT> /*unspecified*/ quoted(const CharT* s, CharT delim = CharT('"'), CharT escape = CharT('\\')); template<class CharT, class Traits, class Allocator> /*unspecified*/ quoted(const basic_string<CharT, Traits, Allocator>& s, CharT delim = CharT('"'), CharT escape = CharT('\\')); template<class CharT, class Traits, class Allocator> /*unspecified*/ quoted(basic_string<CharT, Traits, Allocator>& s, CharT delim = CharT('"'), CharT escape = CharT('\\')); template<class CharT, class Traits> /*unspecified*/ quoted(basic_string_view<CharT, Traits> s, CharT delim = CharT('"'), CharT escape = CharT('\\')); } ``` cpp Standard library header <compare> (C++20) Standard library header <compare> (C++20) ========================================= This header is part of the [language support](../utility "cpp/utility") library. | | | --- | | Concepts | | [three\_way\_comparablethree\_way\_comparable\_with](../utility/compare/three_way_comparable "cpp/utility/compare/three way comparable") (C++20) | specifies that operator `<=>` produces consistent result on given types (concept) | | Classes | | [partial\_ordering](../utility/compare/partial_ordering "cpp/utility/compare/partial ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values (class) | | [weak\_ordering](../utility/compare/weak_ordering "cpp/utility/compare/weak ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is not substitutable (class) | | [strong\_ordering](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering") (C++20) | the result type of 3-way comparison that supports all 6 operators and is substitutable (class) | | [common\_comparison\_category](../utility/compare/common_comparison_category "cpp/utility/compare/common comparison category") (C++20) | the strongest comparison category to which all of the given types can be converted (class template) | | [compare\_three\_way\_result](../utility/compare/compare_three_way_result "cpp/utility/compare/compare three way result") (C++20) | obtains the result type of the three-way comparison operator `<=>` on given types (class template) | | [compare\_three\_way](../utility/compare/compare_three_way "cpp/utility/compare/compare three way") (C++20) | function object implementing `x <=> y` (class) | | Customization point objects | | [strong\_order](../utility/compare/strong_order "cpp/utility/compare/strong order") (C++20) | performs 3-way comparison and produces a result of type `std::strong_ordering` (customization point object) | | [weak\_order](../utility/compare/weak_order "cpp/utility/compare/weak order") (C++20) | performs 3-way comparison and produces a result of type `std::weak_ordering` (customization point object) | | [partial\_order](../utility/compare/partial_order "cpp/utility/compare/partial order") (C++20) | performs 3-way comparison and produces a result of type `std::partial_ordering` (customization point object) | | [compare\_strong\_order\_fallback](../utility/compare/compare_strong_order_fallback "cpp/utility/compare/compare strong order fallback") (C++20) | performs 3-way comparison and produces a result of type `std::strong_ordering`, even if `operator<=>` is unavailable (customization point object) | | [compare\_weak\_order\_fallback](../utility/compare/compare_weak_order_fallback "cpp/utility/compare/compare weak order fallback") (C++20) | performs 3-way comparison and produces a result of type `std::weak_ordering`, even if `operator<=>` is unavailable (customization point object) | | [compare\_partial\_order\_fallback](../utility/compare/compare_partial_order_fallback "cpp/utility/compare/compare partial order fallback") (C++20) | performs 3-way comparison and produces a result of type `std::partial_ordering`, even if `operator<=>` is unavailable (customization point object) | | Functions | | [is\_eqis\_neqis\_ltis\_lteqis\_gtis\_gteq](../utility/compare/named_comparison_functions "cpp/utility/compare/named comparison functions") (C++20) | named comparison functions (function) | ### Synopsis ``` namespace std { // comparison category types class partial_ordering; class weak_ordering; class strong_ordering; // named comparison functions constexpr bool is_eq (partial_ordering cmp) noexcept { return cmp == 0; } constexpr bool is_neq (partial_ordering cmp) noexcept { return cmp != 0; } constexpr bool is_lt (partial_ordering cmp) noexcept { return cmp < 0; } constexpr bool is_lteq(partial_ordering cmp) noexcept { return cmp <= 0; } constexpr bool is_gt (partial_ordering cmp) noexcept { return cmp > 0; } constexpr bool is_gteq(partial_ordering cmp) noexcept { return cmp >= 0; } // common comparison category type template<class... Ts> struct common_comparison_category { using type = /* see description */; }; template<class... Ts> using common_comparison_category_t = typename common_comparison_category<Ts...>::type; // concept three_way_comparable template<class T, class Cat = partial_ordering> concept three_way_comparable = /* see description */; template<class T, class U, class Cat = partial_ordering> concept three_way_comparable_with = /* see description */; // result of three-way comparison template<class T, class U = T> struct compare_three_way_result; template<class T, class U = T> using compare_three_way_result_t = typename compare_three_way_result<T, U>::type; // class compare_three_way struct compare_three_way; // comparison algorithms inline namespace /* unspecified */ { inline constexpr /* unspecified */ strong_order = /* unspecified */; inline constexpr /* unspecified */ weak_order = /* unspecified */; inline constexpr /* unspecified */ partial_order = /* unspecified */; inline constexpr /* unspecified */ compare_strong_order_fallback = /* unspecified */; inline constexpr /* unspecified */ compare_weak_order_fallback = /* unspecified */; inline constexpr /* unspecified */ compare_partial_order_fallback = /* unspecified */; } } ``` #### Concept [`three_way_comparable`](../utility/compare/three_way_comparable "cpp/utility/compare/three way comparable") ``` namespace std { template<class T, class Cat> concept __ComparesAs = // exposition only same_as<common_comparison_category_t<T, Cat>, Cat>; template<class T, class U> concept __PartiallyOrderedWith = // exposition only requires(const remove_reference_t<T>& t, const remove_reference_t<U>& u) { { t < u } -> boolean-testable; { t > u } -> boolean-testable; { t <= u } -> boolean-testable; { t >= u } -> boolean-testable; { u < t } -> boolean-testable; { u > t } -> boolean-testable; { u <= t } -> boolean-testable; { u >= t } -> boolean-testable; }; template<class T, class Cat = partial_ordering> concept three_way_comparable = __WeaklyEqualityComparableWith<T, T> && __PartiallyOrderedWith<T, T> && requires(const remove_reference_t<T>& a, const remove_reference_t<T>& b) { { a <=> b } -> __ComparesAs<Cat>; }; } ``` #### Concept [`three_way_comparable_with`](../utility/compare/three_way_comparable "cpp/utility/compare/three way comparable") ``` namespace std { template<class T, class U, class Cat = partial_ordering> concept three_way_comparable_with = __WeaklyEqualityComparableWith<T, U> && __PartiallyOrderedWith<T, U> && three_way_comparable<T, Cat> && three_way_comparable<U, Cat> && common_reference_with<const remove_reference_t<T>&, const remove_reference_t<U>&> && three_way_comparable< common_reference_t< const remove_reference_t<T>&, const remove_reference_t<U>&>, Cat> && requires(const remove_reference_t<T>& t, const remove_reference_t<U>& u) { { t <=> u } -> __ComparesAs<Cat>; { u <=> t } -> __ComparesAs<Cat>; }; } ``` #### Class `std::partial_ordering` ``` namespace std { class partial_ordering { int value; // exposition only bool is_ordered; // exposition only // exposition-only constructors constexpr explicit partial_ordering(eq v) noexcept : value(int(v)), is_ordered(true) {} // exposition only constexpr explicit partial_ordering(ord v) noexcept : value(int(v)), is_ordered(true) {} // exposition only constexpr explicit partial_ordering(ncmp v) noexcept : value(int(v)), is_ordered(false) {} // exposition only public: // valid values static const partial_ordering less; static const partial_ordering equivalent; static const partial_ordering greater; static const partial_ordering unordered; // comparisons friend constexpr bool operator==(partial_ordering v, /* unspecified */) noexcept; friend constexpr bool operator==(partial_ordering v, partial_ordering w) noexcept = default; friend constexpr bool operator< (partial_ordering v, /* unspecified */) noexcept; friend constexpr bool operator> (partial_ordering v, /* unspecified */) noexcept; friend constexpr bool operator<=(partial_ordering v, /* unspecified */) noexcept; friend constexpr bool operator>=(partial_ordering v, /* unspecified */) noexcept; friend constexpr bool operator< (/* unspecified */, partial_ordering v) noexcept; friend constexpr bool operator> (/* unspecified */, partial_ordering v) noexcept; friend constexpr bool operator<=(/* unspecified */, partial_ordering v) noexcept; friend constexpr bool operator>=(/* unspecified */, partial_ordering v) noexcept; friend constexpr partial_ordering operator<=>(partial_ordering v, /* unspecified */) noexcept; friend constexpr partial_ordering operator<=>(/* unspecified */, partial_ordering v) noexcept; }; // valid values' definitions inline constexpr partial_ordering partial_ordering::less(ord::less); inline constexpr partial_ordering partial_ordering::equivalent(eq::equivalent); inline constexpr partial_ordering partial_ordering::greater(ord::greater); inline constexpr partial_ordering partial_ordering::unordered(ncmp::unordered); } ``` #### Class `std::weak_ordering` ``` namespace std { class weak_ordering { int value; // exposition only // exposition-only constructors constexpr explicit weak_ordering(eq v) noexcept : value(int(v)) {} // exposition only constexpr explicit weak_ordering(ord v) noexcept : value(int(v)) {} // exposition only public: // valid values static const weak_ordering less; static const weak_ordering equivalent; static const weak_ordering greater; // conversions constexpr operator partial_ordering() const noexcept; // comparisons friend constexpr bool operator==(weak_ordering v, /* unspecified */) noexcept; friend constexpr bool operator==(weak_ordering v, weak_ordering w) noexcept = default; friend constexpr bool operator< (weak_ordering v, /* unspecified */) noexcept; friend constexpr bool operator> (weak_ordering v, /* unspecified */) noexcept; friend constexpr bool operator<=(weak_ordering v, /* unspecified */) noexcept; friend constexpr bool operator>=(weak_ordering v, /* unspecified */) noexcept; friend constexpr bool operator< (/* unspecified */, weak_ordering v) noexcept; friend constexpr bool operator> (/* unspecified */, weak_ordering v) noexcept; friend constexpr bool operator<=(/* unspecified */, weak_ordering v) noexcept; friend constexpr bool operator>=(/* unspecified */, weak_ordering v) noexcept; friend constexpr weak_ordering operator<=>(weak_ordering v, /* unspecified */) noexcept; friend constexpr weak_ordering operator<=>(/* unspecified */, weak_ordering v) noexcept; }; // valid values' definitions inline constexpr weak_ordering weak_ordering::less(ord::less); inline constexpr weak_ordering weak_ordering::equivalent(eq::equivalent); inline constexpr weak_ordering weak_ordering::greater(ord::greater); } ``` #### Class `std::strong_ordering` ``` namespace std { class strong_ordering { int value; // exposition only // exposition-only constructors constexpr explicit strong_ordering(eq v) noexcept : value(int(v)) {} // exposition only constexpr explicit strong_ordering(ord v) noexcept : value(int(v)) {} // exposition only public: // valid values static const strong_ordering less; static const strong_ordering equal; static const strong_ordering equivalent; static const strong_ordering greater; // conversions constexpr operator partial_ordering() const noexcept; constexpr operator weak_ordering() const noexcept; // comparisons friend constexpr bool operator==(strong_ordering v, /* unspecified */) noexcept; friend constexpr bool operator==(strong_ordering v, strong_ordering w) noexcept = default; friend constexpr bool operator< (strong_ordering v, /* unspecified */) noexcept; friend constexpr bool operator> (strong_ordering v, /* unspecified */) noexcept; friend constexpr bool operator<=(strong_ordering v, /* unspecified */) noexcept; friend constexpr bool operator>=(strong_ordering v, /* unspecified */) noexcept; friend constexpr bool operator< (/* unspecified */, strong_ordering v) noexcept; friend constexpr bool operator> (/* unspecified */, strong_ordering v) noexcept; friend constexpr bool operator<=(/* unspecified */, strong_ordering v) noexcept; friend constexpr bool operator>=(/* unspecified */, strong_ordering v) noexcept; friend constexpr strong_ordering operator<=>(strong_ordering v, /* unspecified */) noexcept; friend constexpr strong_ordering operator<=>(/* unspecified */, strong_ordering v) noexcept; }; // valid values' definitions inline constexpr strong_ordering strong_ordering::less(ord::less); inline constexpr strong_ordering strong_ordering::equal(eq::equal); inline constexpr strong_ordering strong_ordering::equivalent(eq::equivalent); inline constexpr strong_ordering strong_ordering::greater(ord::greater); } ``` #### Class `[std::compare\_three\_way](../utility/compare/compare_three_way "cpp/utility/compare/compare three way")` ``` namespace std { struct compare_three_way { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` ### See also | | | --- | | [**three-way comparison operator**](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") expression *lhs* `<=>` *rhs* (C++20) | cpp Standard library header <vector> Standard library header <vector> ================================ This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [vector](../container/vector "cpp/container/vector") | dynamic contiguous array (class template) | | [vector<bool>](../container/vector_bool "cpp/container/vector bool") | space-efficient dynamic bitset (class template specialization) | | [std::hash<std::vector<bool>>](../container/vector_bool/hash "cpp/container/vector bool/hash") (C++11) | hash support for `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>` (class template specialization) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/vector/operator_cmp "cpp/container/vector/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the vector (function template) | | [std::swap(std::vector)](../container/vector/swap2 "cpp/container/vector/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::vector)erase\_if(std::vector)](../container/vector/erase2 "cpp/container/vector/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template vector template<class T, class Allocator = allocator<T>> class vector; template<class T, class Allocator> constexpr bool operator==(const vector<T, Allocator>& x, const vector<T, Allocator>& y); template<class T, class Allocator> constexpr /*synth-three-way-result*/<T> operator<=>(const vector<T, Allocator>& x, const vector<T, Allocator>& y); template<class T, class Allocator> constexpr void swap(vector<T, Allocator>& x, vector<T, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class T, class Allocator, class U> constexpr typename vector<T, Allocator>::size_type erase(vector<T, Allocator>& c, const U& value); template<class T, class Allocator, class Predicate> constexpr typename vector<T, Allocator>::size_type erase_if(vector<T, Allocator>& c, Predicate pred); // class vector<bool> template<class Allocator> class vector<bool, Allocator>; // hash support template<class T> struct hash; template<class Allocator> struct hash<vector<bool, Allocator>>; namespace pmr { template<class T> using vector = std::vector<T, polymorphic_allocator<T>>; } } ``` #### Class template `[std::vector](../container/vector "cpp/container/vector")` ``` namespace std { template<class T, class Allocator = allocator<T>> class vector { public: // types using value_type = T; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // construct/copy/destroy constexpr vector() noexcept(noexcept(Allocator())) : vector(Allocator()) { } constexpr explicit vector(const Allocator&) noexcept; constexpr explicit vector(size_type n, const Allocator& = Allocator()); constexpr vector(size_type n, const T& value, const Allocator& = Allocator()); template<class InputIt> constexpr vector(InputIt first, InputIt last, const Allocator& = Allocator()); constexpr vector(const vector& x); constexpr vector(vector&&) noexcept; constexpr vector(const vector&, const Allocator&); constexpr vector(vector&&, const Allocator&); constexpr vector(initializer_list<T>, const Allocator& = Allocator()); constexpr ~vector(); constexpr vector& operator=(const vector& x); constexpr vector& operator=(vector&& x) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value); constexpr vector& operator=(initializer_list<T>); template<class InputIt> constexpr void assign(InputIt first, InputIt last); constexpr void assign(size_type n, const T& u); constexpr void assign(initializer_list<T>); constexpr allocator_type get_allocator() const noexcept; // iterators constexpr iterator begin() noexcept; constexpr const_iterator begin() const noexcept; constexpr iterator end() noexcept; constexpr const_iterator end() const noexcept; constexpr reverse_iterator rbegin() noexcept; constexpr const_reverse_iterator rbegin() const noexcept; constexpr reverse_iterator rend() noexcept; constexpr const_reverse_iterator rend() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept; constexpr const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] constexpr bool empty() const noexcept; constexpr size_type size() const noexcept; constexpr size_type max_size() const noexcept; constexpr size_type capacity() const noexcept; constexpr void resize(size_type sz); constexpr void resize(size_type sz, const T& c); constexpr void reserve(size_type n); constexpr void shrink_to_fit(); // element access constexpr reference operator[](size_type n); constexpr const_reference operator[](size_type n) const; constexpr const_reference at(size_type n) const; constexpr reference at(size_type n); constexpr reference front(); constexpr const_reference front() const; constexpr reference back(); constexpr const_reference back() const; // data access constexpr T* data() noexcept; constexpr const T* data() const noexcept; // modifiers template<class... Args> constexpr reference emplace_back(Args&&... args); constexpr void push_back(const T& x); constexpr void push_back(T&& x); constexpr void pop_back(); template<class... Args> constexpr iterator emplace(const_iterator position, Args&&... args); constexpr iterator insert(const_iterator position, const T& x); constexpr iterator insert(const_iterator position, T&& x); constexpr iterator insert(const_iterator position, size_type n, const T& x); template<class InputIt> constexpr iterator insert(const_iterator position, InputIt first, InputIt last); constexpr iterator insert(const_iterator position, initializer_list<T> il); constexpr iterator erase(const_iterator position); constexpr iterator erase(const_iterator first, const_iterator last); constexpr void swap(vector&) noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value || allocator_traits<Allocator>::is_always_equal::value); constexpr void clear() noexcept; }; template<class InputIt, class Allocator = allocator</*iter-value-type*/<InputIt>>> vector(InputIt, InputIt, Allocator = Allocator()) -> vector</*iter-value-type*/<InputIt>, Allocator>; // swap template<class T, class Allocator> constexpr void swap(vector<T, Allocator>& x, vector<T, Allocator>& y) noexcept(noexcept(x.swap(y))); } ``` #### Class template `[std::vector](../container/vector "cpp/container/vector")`'s specialization for `bool` ``` namespace std { template<class Allocator> class vector<bool, Allocator> { public: // types using value_type = bool; using allocator_type = Allocator; using pointer = /* implementation-defined */; using const_pointer = /* implementation-defined */; using const_reference = bool; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // bit reference class reference { friend class vector; constexpr reference() noexcept; public: constexpr reference(const reference&) = default; constexpr ~reference(); constexpr operator bool() const noexcept; constexpr reference& operator=(const bool x) noexcept; constexpr reference& operator=(const reference& x) noexcept; constexpr void flip() noexcept; // flips the bit }; // construct/copy/destroy constexpr vector() : vector(Allocator()) { } constexpr explicit vector(const Allocator&); constexpr explicit vector(size_type n, const Allocator& = Allocator()); constexpr vector(size_type n, const bool& value, const Allocator& = Allocator()); template<class InputIt> constexpr vector(InputIt first, InputIt last, const Allocator& = Allocator()); constexpr vector(const vector& x); constexpr vector(vector&& x); constexpr vector(const vector&, const Allocator&); constexpr vector(vector&&, const Allocator&); constexpr vector(initializer_list<bool>, const Allocator& = Allocator())); constexpr ~vector(); constexpr vector& operator=(const vector& x); constexpr vector& operator=(vector&& x); constexpr vector& operator=(initializer_list<bool>); template<class InputIt> constexpr void assign(InputIt first, InputIt last); constexpr void assign(size_type n, const bool& t); constexpr void assign(initializer_list<bool>); constexpr allocator_type get_allocator() const noexcept; // iterators constexpr iterator begin() noexcept; constexpr const_iterator begin() const noexcept; constexpr iterator end() noexcept; constexpr const_iterator end() const noexcept; constexpr reverse_iterator rbegin() noexcept; constexpr const_reverse_iterator rbegin() const noexcept; constexpr reverse_iterator rend() noexcept; constexpr const_reverse_iterator rend() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept; constexpr const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] constexpr bool empty() const noexcept; constexpr size_type size() const noexcept; constexpr size_type max_size() const noexcept; constexpr size_type capacity() const noexcept; constexpr void resize(size_type sz, bool c = false); constexpr void reserve(size_type n); constexpr void shrink_to_fit(); // element access constexpr reference operator[](size_type n); constexpr const_reference operator[](size_type n) const; constexpr const_reference at(size_type n) const; constexpr reference at(size_type n); constexpr reference front(); constexpr const_reference front() const; constexpr reference back(); constexpr const_reference back() const; // modifiers template<class... Args> constexpr reference emplace_back(Args&&... args); constexpr void push_back(const bool& x); constexpr void pop_back(); template<class... Args> constexpr iterator emplace(const_iterator position, Args&&... args); constexpr iterator insert(const_iterator position, const bool& x); constexpr iterator insert(const_iterator position, size_type n, const bool& x); template<class InputIt> constexpr iterator insert(const_iterator position, InputIt first, InputIt last); constexpr iterator insert(const_iterator position, initializer_list<bool> il); constexpr iterator erase(const_iterator position); constexpr iterator erase(const_iterator first, const_iterator last); constexpr void swap(vector&); constexpr static void swap(reference x, reference y) noexcept; constexpr void flip() noexcept; // flips all bits constexpr void clear() noexcept; }; } ```
programming_docs
cpp Standard library header <stdfloat> (C++23) Standard library header <stdfloat> (C++23) ========================================== This header is part of the [type support](../types "cpp/types") library, providing [fixed width floating-point types](https://en.cppreference.com/mwiki/index.php?title=cpp/types/floating-point&action=edit&redlink=1 "cpp/types/floating-point (page does not exist)"). | | | --- | | Types | ### Synopsis ``` namespace std { #if defined(__STDCPP_FLOAT16_T__) using float16_t = /* implementation-defined */; #endif #if defined(__STDCPP_FLOAT32_T__) using float32_t = /* implementation-defined */; #endif #if defined(__STDCPP_FLOAT64_T__) using float64_t = /* implementation-defined */; #endif #if defined(__STDCPP_FLOAT128_T__) using float128_t = /* implementation-defined */; #endif #if defined(__STDCPP_BFLOAT16_T__) using bfloat16_t = /* implementation-defined */; #endif } ``` ### References * C++23 standard (ISO/IEC 14882:2023): + 17.5 Header `<stdfloat>` synopsis [stdfloat.syn] cpp Standard library header <cwctype> Standard library header <cwctype> ================================= This header was originally in the C standard library as `<wctype.h>`. This header is part of the [C-style null-terminated wide strings](../string/wide "cpp/string/wide") library. ### Types | | | | --- | --- | | `wctrans_t` | scalar type that holds locale-specific character mapping | | `wctype_t` | scalar type that holds locale-specific character classification | | `wint_t` | integer type that can hold any valid wide character and at least one more value | ### Macros | | | | --- | --- | | WEOF | a non-character value of type wint\_t used to indicate errors (macro constant) | ### Functions | | | --- | | Character classification | | [iswalnum](../string/wide/iswalnum "cpp/string/wide/iswalnum") | checks if a wide character is alphanumeric (function) | | [iswalpha](../string/wide/iswalpha "cpp/string/wide/iswalpha") | checks if a wide character is alphabetic (function) | | [iswlower](../string/wide/iswlower "cpp/string/wide/iswlower") | checks if a wide character is lowercase (function) | | [iswupper](../string/wide/iswupper "cpp/string/wide/iswupper") | checks if a wide character is an uppercase character (function) | | [iswdigit](../string/wide/iswdigit "cpp/string/wide/iswdigit") | checks if a wide character is a digit (function) | | [iswxdigit](../string/wide/iswxdigit "cpp/string/wide/iswxdigit") | checks if a character is a hexadecimal character (function) | | [iswcntrl](../string/wide/iswcntrl "cpp/string/wide/iswcntrl") | checks if a wide character is a control character (function) | | [iswgraph](../string/wide/iswgraph "cpp/string/wide/iswgraph") | checks if a wide character is a graphical character (function) | | [iswspace](../string/wide/iswspace "cpp/string/wide/iswspace") | checks if a wide character is a space character (function) | | [iswblank](../string/wide/iswblank "cpp/string/wide/iswblank") (C++11) | checks if a wide character is a blank character (function) | | [iswprint](../string/wide/iswprint "cpp/string/wide/iswprint") | checks if a wide character is a printing character (function) | | [iswpunct](../string/wide/iswpunct "cpp/string/wide/iswpunct") | checks if a wide character is a punctuation character (function) | | [iswctype](../string/wide/iswctype "cpp/string/wide/iswctype") | classifies a wide character according to the specified LC\_CTYPE category (function) | | [wctype](../string/wide/wctype "cpp/string/wide/wctype") | looks up a character classification category in the current C locale (function) | | Character manipulation | | [towlower](../string/wide/towlower "cpp/string/wide/towlower") | converts a wide character to lowercase (function) | | [towupper](../string/wide/towupper "cpp/string/wide/towupper") | converts a wide character to uppercase (function) | | [towctrans](../string/wide/towctrans "cpp/string/wide/towctrans") | performs character mapping according to the specified LC\_CTYPE mapping category (function) | | [wctrans](../string/wide/wctrans "cpp/string/wide/wctrans") | looks up a character mapping category in the current C locale (function) | cpp Standard library header <filesystem> (C++17) Standard library header <filesystem> (C++17) ============================================ This header is part of the [filesystem support](../filesystem "cpp/filesystem") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | Defined in namespace `std::filesystem` | | [path](../filesystem/path "cpp/filesystem/path") (C++17) | represents a path (class) | | [filesystem\_error](../filesystem/filesystem_error "cpp/filesystem/filesystem error") (C++17) | an exception thrown on file system errors (class) | | [directory\_entry](../filesystem/directory_entry "cpp/filesystem/directory entry") (C++17) | a directory entry (class) | | [directory\_iterator](../filesystem/directory_iterator "cpp/filesystem/directory iterator") (C++17) | an iterator to the contents of the directory (class) | | [recursive\_directory\_iterator](../filesystem/recursive_directory_iterator "cpp/filesystem/recursive directory iterator") (C++17) | an iterator to the contents of a directory and its subdirectories (class) | | [file\_status](../filesystem/file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [space\_info](../filesystem/space_info "cpp/filesystem/space info") (C++17) | information about free and available space on the filesystem (class) | | [file\_type](../filesystem/file_type "cpp/filesystem/file type") (C++17) | the type of a file (enum) | | [perms](../filesystem/perms "cpp/filesystem/perms") (C++17) | identifies file system permissions (enum) | | [perm\_options](../filesystem/perm_options "cpp/filesystem/perm options") (C++17) | specifies semantics of permissions operations (enum) | | [copy\_options](../filesystem/copy_options "cpp/filesystem/copy options") (C++17) | specifies semantics of copy operations (enum) | | [directory\_options](../filesystem/directory_options "cpp/filesystem/directory options") (C++17) | options for iterating directory contents (enum) | | [file\_time\_type](../filesystem/file_time_type "cpp/filesystem/file time type") (C++17) | represents file time values (typedef) | | Defined in namespace `std` | | [std::hash<std::filesystem::path>](../filesystem/path/hash "cpp/filesystem/path/hash") (C++17) | hash support for `[std::filesystem::path](../filesystem/path "cpp/filesystem/path")` (class template specialization) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | Defined in namespace `std` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Functions | | Defined in namespace `std::filesystem` | | [u8path](../filesystem/path/u8path "cpp/filesystem/path/u8path") (C++17)(deprecated in C++20) | creates a `path` from a UTF-8 encoded source (function) | | [absolute](../filesystem/absolute "cpp/filesystem/absolute") (C++17) | composes an absolute path (function) | | [canonicalweakly\_canonical](../filesystem/canonical "cpp/filesystem/canonical") (C++17) | composes a canonical path (function) | | [relativeproximate](../filesystem/relative "cpp/filesystem/relative") (C++17) | composes a relative path (function) | | [copy](../filesystem/copy "cpp/filesystem/copy") (C++17) | copies files or directories (function) | | [copy\_file](../filesystem/copy_file "cpp/filesystem/copy file") (C++17) | copies file contents (function) | | [copy\_symlink](../filesystem/copy_symlink "cpp/filesystem/copy symlink") (C++17) | copies a symbolic link (function) | | [create\_directorycreate\_directories](../filesystem/create_directory "cpp/filesystem/create directory") (C++17)(C++17) | creates new directory (function) | | [create\_hard\_link](../filesystem/create_hard_link "cpp/filesystem/create hard link") (C++17) | creates a hard link (function) | | [create\_symlinkcreate\_directory\_symlink](../filesystem/create_symlink "cpp/filesystem/create symlink") (C++17)(C++17) | creates a symbolic link (function) | | [current\_path](../filesystem/current_path "cpp/filesystem/current path") (C++17) | returns or sets the current working directory (function) | | [exists](../filesystem/exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [equivalent](../filesystem/equivalent "cpp/filesystem/equivalent") (C++17) | checks whether two paths refer to the same file system object (function) | | [file\_size](../filesystem/file_size "cpp/filesystem/file size") (C++17) | returns the size of a file (function) | | [hard\_link\_count](../filesystem/hard_link_count "cpp/filesystem/hard link count") (C++17) | returns the number of hard links referring to the specific file (function) | | [last\_write\_time](../filesystem/last_write_time "cpp/filesystem/last write time") (C++17) | gets or sets the time of the last data modification (function) | | [permissions](../filesystem/permissions "cpp/filesystem/permissions") (C++17) | modifies file access permissions (function) | | [read\_symlink](../filesystem/read_symlink "cpp/filesystem/read symlink") (C++17) | obtains the target of a symbolic link (function) | | [removeremove\_all](../filesystem/remove "cpp/filesystem/remove") (C++17)(C++17) | removes a file or empty directoryremoves a file or directory and all its contents, recursively (function) | | [rename](../filesystem/rename "cpp/filesystem/rename") (C++17) | moves or renames a file or directory (function) | | [resize\_file](../filesystem/resize_file "cpp/filesystem/resize file") (C++17) | changes the size of a regular file by truncation or zero-fill (function) | | [space](../filesystem/space "cpp/filesystem/space") (C++17) | determines available free space on the file system (function) | | [statussymlink\_status](../filesystem/status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [temp\_directory\_path](../filesystem/temp_directory_path "cpp/filesystem/temp directory path") (C++17) | returns a directory suitable for temporary files (function) | | File types | | [is\_block\_file](../filesystem/is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](../filesystem/is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](../filesystem/is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_empty](../filesystem/is_empty "cpp/filesystem/is empty") (C++17) | checks whether the given path refers to an empty file or directory (function) | | [is\_fifo](../filesystem/is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](../filesystem/is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](../filesystem/is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](../filesystem/is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](../filesystem/is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [status\_known](../filesystem/status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | ### Synopsis ``` #include <compare> namespace std::filesystem { // paths class path; // path non-member functions void swap(path& lhs, path& rhs) noexcept; size_t hash_value(const path& p) noexcept; // filesystem errors class filesystem_error; // directory entries class directory_entry; // directory iterators class directory_iterator; // range access for directory iterators directory_iterator begin(directory_iterator iter) noexcept; directory_iterator end(directory_iterator) noexcept; // recursive directory iterators class recursive_directory_iterator; // range access for recursive directory iterators recursive_directory_iterator begin(recursive_directory_iterator iter) noexcept; recursive_directory_iterator end(recursive_directory_iterator) noexcept; // file status class file_status; struct space_info { uintmax_t capacity; uintmax_t free; uintmax_t available; friend bool operator==(const space_info&, const space_info&) = default; }; // enumerations enum class file_type; enum class perms; enum class perm_options; enum class copy_options; enum class directory_options; using file_time_type = chrono::time_point<chrono::file_clock>; // filesystem operations path absolute(const path& p); path absolute(const path& p, error_code& ec); path canonical(const path& p); path canonical(const path& p, error_code& ec); void copy(const path& from, const path& to); void copy(const path& from, const path& to, error_code& ec); void copy(const path& from, const path& to, copy_options options); void copy(const path& from, const path& to, copy_options options, error_code& ec); bool copy_file(const path& from, const path& to); bool copy_file(const path& from, const path& to, error_code& ec); bool copy_file(const path& from, const path& to, copy_options option); bool copy_file(const path& from, const path& to, copy_options option, error_code& ec); void copy_symlink(const path& existing_symlink, const path& new_symlink); void copy_symlink(const path& existing_symlink, const path& new_symlink, error_code& ec) noexcept; bool create_directories(const path& p); bool create_directories(const path& p, error_code& ec); bool create_directory(const path& p); bool create_directory(const path& p, error_code& ec) noexcept; bool create_directory(const path& p, const path& attributes); bool create_directory(const path& p, const path& attributes, error_code& ec) noexcept; void create_directory_symlink(const path& to, const path& new_symlink); void create_directory_symlink(const path& to, const path& new_symlink, error_code& ec) noexcept; void create_hard_link(const path& to, const path& new_hard_link); void create_hard_link(const path& to, const path& new_hard_link, error_code& ec) noexcept; void create_symlink(const path& to, const path& new_symlink); void create_symlink(const path& to, const path& new_symlink, error_code& ec) noexcept; path current_path(); path current_path(error_code& ec); void current_path(const path& p); void current_path(const path& p, error_code& ec) noexcept; bool equivalent(const path& p1, const path& p2); bool equivalent(const path& p1, const path& p2, error_code& ec) noexcept; bool exists(file_status s) noexcept; bool exists(const path& p); bool exists(const path& p, error_code& ec) noexcept; uintmax_t file_size(const path& p); uintmax_t file_size(const path& p, error_code& ec) noexcept; uintmax_t hard_link_count(const path& p); uintmax_t hard_link_count(const path& p, error_code& ec) noexcept; bool is_block_file(file_status s) noexcept; bool is_block_file(const path& p); bool is_block_file(const path& p, error_code& ec) noexcept; bool is_character_file(file_status s) noexcept; bool is_character_file(const path& p); bool is_character_file(const path& p, error_code& ec) noexcept; bool is_directory(file_status s) noexcept; bool is_directory(const path& p); bool is_directory(const path& p, error_code& ec) noexcept; bool is_empty(const path& p); bool is_empty(const path& p, error_code& ec); bool is_fifo(file_status s) noexcept; bool is_fifo(const path& p); bool is_fifo(const path& p, error_code& ec) noexcept; bool is_other(file_status s) noexcept; bool is_other(const path& p); bool is_other(const path& p, error_code& ec) noexcept; bool is_regular_file(file_status s) noexcept; bool is_regular_file(const path& p); bool is_regular_file(const path& p, error_code& ec) noexcept; bool is_socket(file_status s) noexcept; bool is_socket(const path& p); bool is_socket(const path& p, error_code& ec) noexcept; bool is_symlink(file_status s) noexcept; bool is_symlink(const path& p); bool is_symlink(const path& p, error_code& ec) noexcept; file_time_type last_write_time(const path& p); file_time_type last_write_time(const path& p, error_code& ec) noexcept; void last_write_time(const path& p, file_time_type new_time); void last_write_time(const path& p, file_time_type new_time, error_code& ec) noexcept; void permissions(const path& p, perms prms, perm_options opts=perm_options::replace); void permissions(const path& p, perms prms, error_code& ec) noexcept; void permissions(const path& p, perms prms, perm_options opts, error_code& ec); path proximate(const path& p, error_code& ec); path proximate(const path& p, const path& base = current_path()); path proximate(const path& p, const path& base, error_code& ec); path read_symlink(const path& p); path read_symlink(const path& p, error_code& ec); path relative(const path& p, error_code& ec); path relative(const path& p, const path& base = current_path()); path relative(const path& p, const path& base, error_code& ec); bool remove(const path& p); bool remove(const path& p, error_code& ec) noexcept; uintmax_t remove_all(const path& p); uintmax_t remove_all(const path& p, error_code& ec); void rename(const path& from, const path& to); void rename(const path& from, const path& to, error_code& ec) noexcept; void resize_file(const path& p, uintmax_t size); void resize_file(const path& p, uintmax_t size, error_code& ec) noexcept; space_info space(const path& p); space_info space(const path& p, error_code& ec) noexcept; file_status status(const path& p); file_status status(const path& p, error_code& ec) noexcept; bool status_known(file_status s) noexcept; file_status symlink_status(const path& p); file_status symlink_status(const path& p, error_code& ec) noexcept; path temp_directory_path(); path temp_directory_path(error_code& ec); path weakly_canonical(const path& p); path weakly_canonical(const path& p, error_code& ec); } // hash support namespace std { template<class T> struct hash; template<> struct hash<filesystem::path>; } namespace std::ranges { template<> inline constexpr bool enable_borrowed_range<filesystem::directory_iterator> = true; template<> inline constexpr bool enable_borrowed_range<filesystem::recursive_directory_iterator> = true; template<> inline constexpr bool enable_view<filesystem::directory_iterator> = true; template<> inline constexpr bool enable_view<filesystem::recursive_directory_iterator> = true; } // deprecated namespace std::filesystem { template<class Source> path u8path(const Source& source); template<class InputIterator> path u8path(InputIt first, InputIt last); } ``` #### Class `[std::filesystem::path](../filesystem/path "cpp/filesystem/path")` ``` namespace std::filesystem { class path { public: using value_type = /* see description */; using string_type = basic_string<value_type>; static constexpr value_type preferred_separator = /* see description */; // enumeration format enum format; // constructors and destructor path() noexcept; path(const path& p); path(path&& p) noexcept; path(string_type&& source, format fmt = auto_format); template<class Source> path(const Source& source, format fmt = auto_format); template<class InputIt> path(InputIt first, InputIt last, format fmt = auto_format); template<class Source> path(const Source& source, const locale& loc, format fmt = auto_format); template<class InputIt> path(InputIt first, InputIt last, const locale& loc, format fmt = auto_format); ~path(); // assignments path& operator=(const path& p); path& operator=(path&& p) noexcept; path& operator=(string_type&& source); path& assign(string_type&& source); template<class Source> path& operator=(const Source& source); template<class Source> path& assign(const Source& source); template<class InputIt> path& assign(InputIt first, InputIt last); // appends path& operator/=(const path& p); template<class Source> path& operator/=(const Source& source); template<class Source> path& append(const Source& source); template<class InputIt> path& append(InputIt first, InputIt last); // concatenation path& operator+=(const path& x); path& operator+=(const string_type& x); path& operator+=(basic_string_view<value_type> x); path& operator+=(const value_type* x); path& operator+=(value_type x); template<class Source> path& operator+=(const Source& x); template<class ECharT> path& operator+=(ECharT x); template<class Source> path& concat(const Source& x); template<class InputIt> path& concat(InputIt first, InputIt last); // modifiers void clear() noexcept; path& make_preferred(); path& remove_filename(); path& replace_filename(const path& replacement); path& replace_extension(const path& replacement = path()); void swap(path& rhs) noexcept; // non-member operators friend bool operator==(const path& lhs, const path& rhs) noexcept; friend strong_ordering operator<=>(const path& lhs, const path& rhs) noexcept; friend path operator/ (const path& lhs, const path& rhs); // native format observers const string_type& native() const noexcept; const value_type* c_str() const noexcept; operator string_type() const; template<class ECharT, class Traits = char_traits<ECharT>, class Allocator = allocator<ECharT>> basic_string<ECharT, Traits, Allocator> string(const Allocator& a = Allocator()) const; std::string string() const; std::wstring wstring() const; std::u8string u8string() const; std::u16string u16string() const; std::u32string u32string() const; // generic format observers template<class ECharT, class Traits = char_traits<ECharT>, class Allocator = allocator<ECharT>> basic_string<ECharT, Traits, Allocator> generic_string(const Allocator& a = Allocator()) const; std::string generic_string() const; std::wstring generic_wstring() const; std::u8string generic_u8string() const; std::u16string generic_u16string() const; std::u32string generic_u32string() const; // compare int compare(const path& p) const noexcept; int compare(const string_type& s) const; int compare(basic_string_view<value_type> s) const; int compare(const value_type* s) const; // decomposition path root_name() const; path root_directory() const; path root_path() const; path relative_path() const; path parent_path() const; path filename() const; path stem() const; path extension() const; // query [[nodiscard]] bool empty() const noexcept; bool has_root_name() const; bool has_root_directory() const; bool has_root_path() const; bool has_relative_path() const; bool has_parent_path() const; bool has_filename() const; bool has_stem() const; bool has_extension() const; bool is_absolute() const; bool is_relative() const; // generation path lexically_normal() const; path lexically_relative(const path& base) const; path lexically_proximate(const path& base) const; // iterators class iterator; using const_iterator = iterator; iterator begin() const; iterator end() const; // path inserter and extractor template<class CharT, class Traits> friend basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& os, const path& p); template<class CharT, class Traits> friend basic_istream<CharT, Traits>& operator>>(basic_istream<CharT, Traits>& is, path& p); }; } ``` #### Class `[std::filesystem::filesystem\_error](../filesystem/filesystem_error "cpp/filesystem/filesystem error")` ``` namespace std::filesystem { class filesystem_error : public system_error { public: filesystem_error(const string& what_arg, error_code ec); filesystem_error(const string& what_arg, const path& p1, error_code ec); filesystem_error(const string& what_arg, const path& p1, const path& p2, error_code ec); const path& path1() const noexcept; const path& path2() const noexcept; const char* what() const noexcept override; }; } ``` #### Class `[std::filesystem::directory\_entry](../filesystem/directory_entry "cpp/filesystem/directory entry")` ``` namespace std::filesystem { class directory_entry { public: // constructors and destructor directory_entry() noexcept = default; directory_entry(const directory_entry&) = default; directory_entry(directory_entry&&) noexcept = default; explicit directory_entry(const filesystem::path& p); directory_entry(const filesystem::path& p, error_code& ec); ~directory_entry(); // assignments directory_entry& operator=(const directory_entry&) = default; directory_entry& operator=(directory_entry&&) noexcept = default; // modifiers void assign(const filesystem::path& p); void assign(const filesystem::path& p, error_code& ec); void replace_filename(const filesystem::path& p); void replace_filename(const filesystem::path& p, error_code& ec); void refresh(); void refresh(error_code& ec) noexcept; // observers const filesystem::path& path() const noexcept; operator const filesystem::path&() const noexcept; bool exists() const; bool exists(error_code& ec) const noexcept; bool is_block_file() const; bool is_block_file(error_code& ec) const noexcept; bool is_character_file() const; bool is_character_file(error_code& ec) const noexcept; bool is_directory() const; bool is_directory(error_code& ec) const noexcept; bool is_fifo() const; bool is_fifo(error_code& ec) const noexcept; bool is_other() const; bool is_other(error_code& ec) const noexcept; bool is_regular_file() const; bool is_regular_file(error_code& ec) const noexcept; bool is_socket() const; bool is_socket(error_code& ec) const noexcept; bool is_symlink() const; bool is_symlink(error_code& ec) const noexcept; uintmax_t file_size() const; uintmax_t file_size(error_code& ec) const noexcept; uintmax_t hard_link_count() const; uintmax_t hard_link_count(error_code& ec) const noexcept; file_time_type last_write_time() const; file_time_type last_write_time(error_code& ec) const noexcept; file_status status() const; file_status status(error_code& ec) const noexcept; file_status symlink_status() const; file_status symlink_status(error_code& ec) const noexcept; bool operator==(const directory_entry& rhs) const noexcept; strong_ordering operator<=>(const directory_entry& rhs) const noexcept; // inserter template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const directory_entry& d); private: filesystem::path pathobject; // exposition only friend class directory_iterator; // exposition only }; } ``` #### Class `[std::filesystem::directory\_iterator](../filesystem/directory_iterator "cpp/filesystem/directory iterator")` ``` namespace std::filesystem { class directory_iterator { public: using iterator_category = input_iterator_tag; using value_type = directory_entry; using difference_type = ptrdiff_t; using pointer = const directory_entry*; using reference = const directory_entry&; // member functions directory_iterator() noexcept; explicit directory_iterator(const path& p); directory_iterator(const path& p, directory_options options); directory_iterator(const path& p, error_code& ec); directory_iterator(const path& p, directory_options options, error_code& ec); directory_iterator(const directory_iterator& rhs); directory_iterator(directory_iterator&& rhs) noexcept; ~directory_iterator(); directory_iterator& operator=(const directory_iterator& rhs); directory_iterator& operator=(directory_iterator&& rhs) noexcept; const directory_entry& operator*() const; const directory_entry* operator->() const; directory_iterator& operator++(); directory_iterator& increment(error_code& ec); // other members as required by input iterators }; } ``` #### Class `[std::filesystem::recursive\_directory\_iterator](../filesystem/recursive_directory_iterator "cpp/filesystem/recursive directory iterator")` ``` namespace std::filesystem { class recursive_directory_iterator { public: using iterator_category = input_iterator_tag; using value_type = directory_entry; using difference_type = ptrdiff_t; using pointer = const directory_entry*; using reference = const directory_entry&; // constructors and destructor recursive_directory_iterator() noexcept; explicit recursive_directory_iterator(const path& p); recursive_directory_iterator(const path& p, directory_options options); recursive_directory_iterator(const path& p, directory_options options, error_code& ec); recursive_directory_iterator(const path& p, error_code& ec); recursive_directory_iterator(const recursive_directory_iterator& rhs); recursive_directory_iterator(recursive_directory_iterator&& rhs) noexcept; ~recursive_directory_iterator(); // observers directory_options options() const; int depth() const; bool recursion_pending() const; const directory_entry& operator*() const; const directory_entry* operator->() const; // modifiers recursive_directory_iterator& operator=(const recursive_directory_iterator& rhs); recursive_directory_iterator& operator=(recursive_directory_iterator&& rhs) noexcept; recursive_directory_iterator& operator++(); recursive_directory_iterator& increment(error_code& ec); void pop(); void pop(error_code& ec); void disable_recursion_pending(); // other members as required by input iterators }; } ``` #### Class `[std::filesystem::file\_status](../filesystem/file_status "cpp/filesystem/file status")` ``` namespace std::filesystem { class file_status { public: // constructors and destructor file_status() noexcept : file_status(file_type::none) {} explicit file_status(file_type ft, perms prms = perms::unknown) noexcept; file_status(const file_status&) noexcept = default; file_status(file_status&&) noexcept = default; ~file_status(); // assignments file_status& operator=(const file_status&) noexcept = default; file_status& operator=(file_status&&) noexcept = default; // modifiers void type(file_type ft) noexcept; void permissions(perms prms) noexcept; // observers file_type type() const noexcept; perms permissions() const noexcept; friend bool operator==(const file_status& lhs, const file_status& rhs) noexcept { return lhs.type() == rhs.type() && lhs.permissions() == rhs.permissions(); } }; } ```
programming_docs
cpp Standard library header <mdspan> (C++23) Standard library header <mdspan> (C++23) ======================================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Classes | | [mdspan](https://en.cppreference.com/mwiki/index.php?title=cpp/container/mdspan&action=edit&redlink=1 "cpp/container/mdspan (page does not exist)") (C++23) | a multi-dimensional non-owning array view (class template) | | [extents](https://en.cppreference.com/mwiki/index.php?title=cpp/container/mdspan/extents&action=edit&redlink=1 "cpp/container/mdspan/extents (page does not exist)") (C++23) | a descriptor of a multidimensional index space of some rank (class template) | | [layout\_left](https://en.cppreference.com/mwiki/index.php?title=cpp/container/mdspan/layout_left&action=edit&redlink=1 "cpp/container/mdspan/layout left (page does not exist)") (C++23) | a layout mapping where the leftmost extent has stride `1`, and strides increase left-to-right as the product of extents (class) | | [layout\_right](https://en.cppreference.com/mwiki/index.php?title=cpp/container/mdspan/layout_right&action=edit&redlink=1 "cpp/container/mdspan/layout right (page does not exist)") (C++23) | a layout mapping where the rightmost extent has stride `1`, and strides increase right-to-left as the product of extents (class) | | [layout\_stride](https://en.cppreference.com/mwiki/index.php?title=cpp/container/mdspan/layout_stride&action=edit&redlink=1 "cpp/container/mdspan/layout stride (page does not exist)") (C++23) | a layout mapping with user-defined strides (class) | | [default\_accessor](https://en.cppreference.com/mwiki/index.php?title=cpp/container/mdspan/default_accessor&action=edit&redlink=1 "cpp/container/mdspan/default accessor (page does not exist)") (C++23) | a type for indexed access to elements of `mdspan` (class template) | ### Synopsis ``` namespace std { // class template extents template<class IndexType, size_t... Extents> class extents; // alias template dextents template<class IndexType, size_t Rank> using dextents = /* see description */; // layout mapping struct layout_left; struct layout_right; struct layout_stride; // class template default_accessor template<class ElementType> class default_accessor; // class template mdspan template<class ElementType, class Extents, class LayoutPolicy = layout_right, class AccessorPolicy = default_accessor<ElementType>> class mdspan; } ``` #### Class template `std::mdspan` ``` namespace std { template<class ElementType, class Extents, class LayoutPolicy, class AccessorPolicy> class mdspan { public: using extents_type = Extents; using layout_type = LayoutPolicy; using accessor_type = AccessorPolicy; using mapping_type = typename layout_type::template mapping<extents_type>; using element_type = ElementType; using value_type = remove_cv_t<element_type>; using index_type = typename extents_type::index_type; using size_type = typename extents_type::size_type; using rank_type = typename extents_type::rank_type; using data_handle_type = typename accessor_type::data_handle_type; using reference = typename accessor_type::reference; static constexpr rank_type rank() noexcept { return extents_type::rank(); } static constexpr rank_type rank_dynamic() noexcept { return extents_type::rank_dynamic(); } static constexpr size_t static_extent(rank_type r) noexcept { return extents_type::static_extent(r); } constexpr index_type extent(rank_type r) const noexcept { return extents().extent(r); } // constructors constexpr mdspan(); constexpr mdspan(const mdspan& rhs) = default; constexpr mdspan(mdspan&& rhs) = default; template<class... OtherIndexTypes> constexpr explicit mdspan(data_handle_type ptr, OtherIndexTypes... exts); template<class OtherIndexType, size_t N> constexpr explicit(N != rank_dynamic()) mdspan(data_handle_type p, span<OtherIndexType, N> exts); template<class OtherIndexType, size_t N> constexpr explicit(N != rank_dynamic()) mdspan(data_handle_type p, const array<OtherIndexType, N>& exts); constexpr mdspan(data_handle_type p, const extents_type& ext); constexpr mdspan(data_handle_type p, const mapping_type& m); constexpr mdspan(data_handle_type p, const mapping_type& m, const accessor_type& a); template<class OtherElementType, class OtherExtents, class OtherLayoutPolicy, class OtherAccessorPolicy> constexpr explicit(/* see description */) mdspan(const mdspan<OtherElementType, OtherExtents, OtherLayoutPolicy, OtherAccessorPolicy>& other); constexpr mdspan& operator=(const mdspan& rhs) = default; constexpr mdspan& operator=(mdspan&& rhs) = default; // members template<class... OtherIndexTypes> constexpr reference operator[](OtherIndexTypes... indices) const; template<class OtherIndexType> constexpr reference operator[](span<OtherIndexType, rank()> indices) const; template<class OtherIndexType> constexpr reference operator[](const array<OtherIndexType, rank()>& indices) const; constexpr size_type size() const noexcept; [[nodiscard]] constexpr bool empty() const noexcept; friend constexpr void swap(mdspan& x, mdspan& y) noexcept; constexpr const extents_type& extents() const noexcept { return map_.extents(); } constexpr const data_handle_type& data_handle() const noexcept { return ptr_; } constexpr const mapping_type& mapping() const noexcept { return map_; } constexpr const accessor_type& accessor() const noexcept { return acc_; } static constexpr bool is_always_unique() { return mapping_type::is_always_unique(); } static constexpr bool is_always_exhaustive() { return mapping_type::is_always_exhaustive(); } static constexpr bool is_always_strided() { return mapping_type::is_always_strided(); } constexpr bool is_unique() const { return map_.is_unique(); } constexpr bool is_exhaustive() const { return map_.is_exhaustive(); } constexpr bool is_strided() const { return map_.is_strided(); } constexpr index_type stride(rank_type r) const { return map_.stride(r); } private: accessor_type acc_; // exposition only mapping_type map_; // exposition only data_handle_type ptr_; // exposition only }; template<class CArray> requires(is_array_v<CArray> && rank_v<CArray> == 1) mdspan(CArray&) -> mdspan<remove_all_extents_t<CArray>, extents<size_t, extent_v<CArray, 0>>>; template<class Pointer> requires(is_pointer_v<remove_reference_t<Pointer>>) mdspan(Pointer&&) -> mdspan<remove_pointer_t<remove_reference_t<Pointer>>, extents<size_t>>; template<class ElementType, class... Integrals> requires((is_convertible_v<Integrals, size_t> && ...) && sizeof...(Integrals) > 0) explicit mdspan(ElementType*, Integrals...) -> mdspan<ElementType, dextents<size_t, sizeof...(Integrals)>>; template<class ElementType, class OtherIndexType, size_t N> mdspan(ElementType*, span<OtherIndexType, N>) -> mdspan<ElementType, dextents<size_t, N>>; template<class ElementType, class OtherIndexType, size_t N> mdspan(ElementType*, const array<OtherIndexType, N>&) -> mdspan<ElementType, dextents<size_t, N>>; template<class ElementType, class IndexType, size_t... ExtentsPack> mdspan(ElementType*, const extents<IndexType, ExtentsPack...>&) -> mdspan<ElementType, extents<IndexType, ExtentsPack...>>; template<class ElementType, class MappingType> mdspan(ElementType*, const MappingType&) -> mdspan<ElementType, typename MappingType::extents_type, typename MappingType::layout_type>; template<class MappingType, class AccessorType> mdspan(const typename AccessorType::data_handle_type&, const MappingType&, const AccessorType&) -> mdspan<typename AccessorType::element_type, typename MappingType::extents_type, typename MappingType::layout_type, AccessorType>; } ``` #### Class template `std::extents` ``` namespace std { template<class IndexType, size_t... Extents> class extents { public: using index_type = IndexType; using size_type = make_unsigned_t<index_type>; using rank_type = size_t; // observers of the multidimensional index space static constexpr rank_type rank() noexcept { return sizeof...(Extents); } static constexpr rank_type rank_dynamic() noexcept { return /*dynamic-index*/(rank()); } static constexpr size_t static_extent(rank_type) noexcept; constexpr index_type extent(rank_type) const noexcept; // constructors constexpr extents() noexcept = default; template<class OtherIndexType, size_t... OtherExtents> constexpr explicit(/* see description */) extents(const extents<OtherIndexType, OtherExtents...>&) noexcept; template<class... OtherIndexTypes> constexpr explicit extents(OtherIndexTypes...) noexcept; template<class OtherIndexType, size_t N> constexpr explicit(N != rank_dynamic()) extents(span<OtherIndexType, N>) noexcept; template<class OtherIndexType, size_t N> constexpr explicit(N != rank_dynamic()) extents(const array<OtherIndexType, N>&) noexcept; // comparison operators template<class OtherIndexType, size_t... OtherExtents> friend constexpr bool operator==(const extents&, const extents<OtherIndexType, OtherExtents...>&) noexcept; // exposition-only helpers constexpr size_t /*fwd-prod-of-extents*/(rank_type) const noexcept; // exposition only constexpr size_t /*rev-prod-of-extents*/(rank_type) const noexcept; // exposition only template<class OtherIndexType> static constexpr auto /*index-cast*/(OtherIndexType&&) noexcept; // exposition only private: static constexpr rank_type /*dynamic-index*/(rank_type) noexcept; // exposition only static constexpr rank_type /*dynamic-index-inv*/(rank_type) noexcept; // exposition only array<index_type, rank_dynamic()>/*dynamic-extents*/{}; // exposition only }; template<class... Integrals> explicit extents(Integrals...) -> /* see description */; } ``` #### Layout mapping policies ``` namespace std { struct layout_left { template<class Extents> class mapping; }; struct layout_right { template<class Extents> class mapping; }; struct layout_stride { template<class Extents> class mapping; }; } ``` #### Class template `std::layout_left::mapping` ``` namespace std { template<class Extents> class layout_left::mapping { public: using extents_type = Extents; using index_type = typename extents_type::index_type; using size_type = typename extents_type::size_type; using rank_type = typename extents_type::rank_type; using layout_type = layout_left; // constructors constexpr mapping() noexcept = default; constexpr mapping(const mapping&) noexcept = default; constexpr mapping(const extents_type&) noexcept; template<class OtherExtents> constexpr explicit(!is_convertible_v<OtherExtents, extents_type>) mapping(const mapping<OtherExtents>&) noexcept; template<class OtherExtents> constexpr explicit(/* see description */) mapping(const layout_right::mapping<OtherExtents>&) noexcept; template<class OtherExtents> explicit(extents_type::rank() > 0) constexpr mapping(const layout_stride::mapping<OtherExtents>&); constexpr mapping& operator=(const mapping&) noexcept = default; // observers constexpr const extents_type& extents() const noexcept { return extents_; } constexpr index_type required_span_size() const noexcept; template<class... Indices> constexpr index_type operator()(Indices...) const noexcept; static constexpr bool is_always_unique() noexcept { return true; } static constexpr bool is_always_exhaustive() noexcept { return true; } static constexpr bool is_always_strided() noexcept { return true; } static constexpr bool is_unique() noexcept { return true; } static constexpr bool is_exhaustive() noexcept { return true; } static constexpr bool is_strided() noexcept { return true; } constexpr index_type stride(rank_type) const noexcept; template<class OtherExtents> friend constexpr bool operator==(const mapping&, const mapping<OtherExtents>&) noexcept; private: extents_type extents_{}; // exposition only }; } ``` #### Class template `std::layout_right::mapping` ``` namespace std { template<class Extents> class layout_right::mapping { public: using extents_type = Extents; using index_type = typename extents_type::index_type; using size_type = typename extents_type::size_type; using rank_type = typename extents_type::rank_type; using layout_type = layout_right; // constructors constexpr mapping() noexcept = default; constexpr mapping(const mapping&) noexcept = default; constexpr mapping(const extents_type&) noexcept; template<class OtherExtents> constexpr explicit(!is_convertible_v<OtherExtents, extents_type>) mapping(const mapping<OtherExtents>&) noexcept; template<class OtherExtents> constexpr explicit(/* see description */) mapping(const layout_left::mapping<OtherExtents>&) noexcept; template<class OtherExtents> constexpr explicit(extents_type::rank() > 0) mapping(const layout_stride::mapping<OtherExtents>&) noexcept; constexpr mapping& operator=(const mapping&) noexcept = default; // observers constexpr const extents_type& extents() const noexcept { return extents_; } constexpr index_type required_span_size() const noexcept; template<class... Indices> constexpr index_type operator()(Indices...) const noexcept; static constexpr bool is_always_unique() noexcept { return true; } static constexpr bool is_always_exhaustive() noexcept { return true; } static constexpr bool is_always_strided() noexcept { return true; } static constexpr bool is_unique() noexcept { return true; } static constexpr bool is_exhaustive() noexcept { return true; } static constexpr bool is_strided() noexcept { return true; } constexpr index_type stride(rank_type) const noexcept; template<class OtherExtents> friend constexpr bool operator==(const mapping&, const mapping<OtherExtents>&) noexcept; private: extents_type extents_{}; // exposition only }; } ``` #### Class template `std::layout_stride::mapping` ``` namespace std { template<class Extents> class layout_stride::mapping { public: using extents_type = Extents; using index_type = typename extents_type::index_type; using size_type = typename extents_type::size_type; using rank_type = typename extents_type::rank_type; using layout_type = layout_stride; private: static constexpr rank_type rank_ = extents_type::rank(); // exposition only public: // constructors constexpr mapping() noexcept = default; constexpr mapping(const mapping&) noexcept = default; template<class OtherIndexType> constexpr mapping(const extents_type&, span<OtherIndexType, rank_>) noexcept; template<class OtherIndexType> constexpr mapping(const extents_type&, const array<OtherIndexType, rank_>&) noexcept; template<class StridedLayoutMapping> constexpr explicit(/* see description */) mapping( const StridedLayoutMapping&) noexcept; constexpr mapping& operator=(const mapping&) noexcept = default; // observers constexpr const extents_type& extents() const noexcept { return extents_; } constexpr array<index_type, rank_> strides() const noexcept { return strides_; } constexpr index_type required_span_size() const noexcept; template<class... Indices> constexpr index_type operator()(Indices...) const noexcept; static constexpr bool is_always_unique() noexcept { return true; } static constexpr bool is_always_exhaustive() noexcept { return false; } static constexpr bool is_always_strided() noexcept { return true; } static constexpr bool is_unique() noexcept { return true; } constexpr bool is_exhaustive() const noexcept; static constexpr bool is_strided() noexcept { return true; } constexpr index_type stride(rank_type i) const noexcept { return strides_[i]; } template<class OtherMapping> friend constexpr bool operator==(const mapping&, const OtherMapping&) noexcept; private: extents_type extents_{}; // exposition only array<index_type, rank_> strides_{}; // exposition only }; } ``` #### Exposition-only helpers ``` template<class T> constexpr bool /*is-extents*/ = false; // exposition only template<class SizeType, size_t... Args> constexpr bool /*is-extents*/<extents<IndexType, Args...>> = true; // exposition only template<class M> concept /*layout-mapping-alike*/ = requires { // exposition only requires /*is-extents*/<typename M::extents_type>; { M::is_always_strided() } -> same_as<bool>; { M::is_always_exhaustive() } -> same_as<bool>; { M::is_always_unique() } -> same_as<bool>; bool_constant<M::is_always_strided()>::value; bool_constant<M::is_always_exhaustive()>::value; bool_constant<M::is_always_unique()>::value; }; ``` #### Class template `std::default_accessor` ``` namespace std { template<class ElementType> struct default_accessor { using offset_policy = default_accessor; using element_type = ElementType; using reference = ElementType&; using data_handle_type = ElementType*; constexpr default_accessor() noexcept = default; template<class OtherElementType> constexpr default_accessor(default_accessor<OtherElementType>) noexcept; constexpr reference access(data_handle_type p, size_t i) const noexcept; constexpr data_handle_type offset(data_handle_type p, size_t i) const noexcept; }; } ``` ### References * C++23 standard (ISO/IEC 14882:2023): + 24.7.4 Header `<mdspan>` synopsis [mdspan.syn] cpp Standard library header <cstdarg> Standard library header <cstdarg> ================================= This header was originally in the C standard library as `<stdarg.h>`. This header provides support for [C-style variadic functions](../utility/variadic "cpp/utility/variadic"). | | | --- | | Types | | [va\_list](../utility/variadic/va_list "cpp/utility/variadic/va list") | holds the information needed by va\_start, va\_arg, va\_end, and va\_copy (typedef) | | Macros | | [va\_start](../utility/variadic/va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_arg](../utility/variadic/va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [va\_copy](../utility/variadic/va_copy "cpp/utility/variadic/va copy") (C++11) | makes a copy of the variadic function arguments (function macro) | | [va\_end](../utility/variadic/va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | ### Synopsis ``` namespace std { using va_list = /*see description*/ ; } #define va_arg(V, P) /*see description*/ #define va_copy(VDST, VSRC) /*see description*/ #define va_end(V) /*see description*/ #define va_start(V, P) /*see description*/ ```
programming_docs
cpp Standard library header <semaphore> (C++20) Standard library header <semaphore> (C++20) =========================================== This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [counting\_semaphore](../thread/counting_semaphore "cpp/thread/counting semaphore") (C++20) | semaphore that models a non-negative resource count (class template) | | [binary\_semaphore](../thread/counting_semaphore "cpp/thread/counting semaphore") (C++20) | semaphore that has only two states (typedef) | ### Synopsis ``` namespace std { template<ptrdiff_t LeastMaxValue = /* implementation-defined */> class counting_semaphore; using binary_semaphore = counting_semaphore<1>; } ``` #### Class template `[std::counting\_semaphore](../thread/counting_semaphore "cpp/thread/counting semaphore")` ``` namespace std { template<ptrdiff_t LeastMaxValue = /* implementation-defined */> class counting_semaphore { public: static constexpr ptrdiff_t max() noexcept; constexpr explicit counting_semaphore(ptrdiff_t desired); ~counting_semaphore(); counting_semaphore(const counting_semaphore&) = delete; counting_semaphore& operator=(const counting_semaphore&) = delete; void release(ptrdiff_t update = 1); void acquire(); bool try_acquire() noexcept; template<class Rep, class Period> bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time); private: ptrdiff_t counter; // exposition only }; } ``` cpp Standard library header <charconv> (C++17) Standard library header <charconv> (C++17) ========================================== This header is part of the [strings](../string "cpp/string") library. | | | --- | | Classes | | [chars\_format](../utility/chars_format "cpp/utility/chars format") (C++17) | specifies formatting for `std::to_chars` and `std::from_chars` (enum) | | Functions | | [from\_chars](../utility/from_chars "cpp/utility/from chars") (C++17) | converts a character sequence to an integer or floating-point value (function) | | [to\_chars](../utility/to_chars "cpp/utility/to chars") (C++17) | converts an integer or floating-point value to a character sequence (function) | ### Synopsis ``` namespace std { // floating-point format for primitive numerical conversion enum class chars_format { scientific = /* unspecified */, fixed = /* unspecified */, hex = /* unspecified */, general = fixed | scientific }; // primitive numerical output conversion struct to_chars_result { char* ptr; errc ec; friend bool operator==(const to_chars_result&, const to_chars_result&) = default; }; constexpr to_chars_result to_chars(char* first, char* last, /* see description */ value, int base = 10); to_chars_result to_chars(char* first, char* last, bool value, int base = 10) = delete; to_chars_result to_chars(char* first, char* last, float value); to_chars_result to_chars(char* first, char* last, double value); to_chars_result to_chars(char* first, char* last, long double value); to_chars_result to_chars(char* first, char* last, float value, chars_format fmt); to_chars_result to_chars(char* first, char* last, double value, chars_format fmt); to_chars_result to_chars(char* first, char* last, long double value, chars_format fmt); to_chars_result to_chars(char* first, char* last, float value, chars_format fmt, int precision); to_chars_result to_chars(char* first, char* last, double value, chars_format fmt, int precision); to_chars_result to_chars(char* first, char* last, long double value, chars_format fmt, int precision); // primitive numerical input conversion struct from_chars_result { const char* ptr; errc ec; friend bool operator==(const from_chars_result&, const from_chars_result&) = default; }; constexpr from_chars_result from_chars(const char* first, const char* last, /* see description */& value, int base = 10); from_chars_result from_chars(const char* first, const char* last, float& value, chars_format fmt = chars_format::general); from_chars_result from_chars(const char* first, const char* last, double& value, chars_format fmt = chars_format::general); from_chars_result from_chars(const char* first, const char* last, long double& value, chars_format fmt = chars_format::general); } ``` cpp Standard library header <any> (C++17) Standard library header <any> (C++17) ===================================== This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Classes | | [any](../utility/any "cpp/utility/any") (C++17) | Objects that hold instances of any [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") type. (class) | | [bad\_any\_cast](../utility/any/bad_any_cast "cpp/utility/any/bad any cast") (C++17) | exception thrown by the value-returning forms of `any_cast` on a type mismatch (class) | | Functions | | [std::swap(std::any)](../utility/any/swap2 "cpp/utility/any/swap2") (C++17) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function) | | [make\_any](../utility/any/make_any "cpp/utility/any/make any") (C++17) | creates an `any` object (function template) | | [any\_cast](../utility/any/any_cast "cpp/utility/any/any cast") (C++17) | type-safe access to the contained object (function template) | ### Synopsis ``` namespace std { // class bad_any_cast class bad_any_cast; // class any class any; // non-member functions void swap(any& x, any& y) noexcept; template<class T, class... Args> any make_any(Args&&... args); template<class T, class U, class... Args> any make_any(initializer_list<U> il, Args&&... args); template<class T> T any_cast(const any& operand); template<class T> T any_cast(any& operand); template<class T> T any_cast(any&& operand); template<class T> const T* any_cast(const any* operand) noexcept; template<class T> T* any_cast(any* operand) noexcept; } ``` #### Class `[std::bad\_any\_cast](../utility/any/bad_any_cast "cpp/utility/any/bad any cast")` ``` namespace std { class bad_any_cast : public bad_cast { public: // see [exception] for the specification of the special member functions const char* what() const noexcept override; }; } ``` #### Class `[std::any](../utility/any "cpp/utility/any")` ``` namespace std { class any { public: // construction and destruction constexpr any() noexcept; any(const any& other); any(any&& other) noexcept; template<class T> any(T&& value); template<class T, class... Args> explicit any(in_place_type_t<T>, Args&&...); template<class T, class U, class... Args> explicit any(in_place_type_t<T>, initializer_list<U>, Args&&...); ~any(); // assignments any& operator=(const any& rhs); any& operator=(any&& rhs) noexcept; template<class T> any& operator=(T&& rhs); // modifiers template<class T, class... Args> decay_t<T>& emplace(Args&&...); template<class T, class U, class... Args> decay_t<T>& emplace(initializer_list<U>, Args&&...); void reset() noexcept; void swap(any& rhs) noexcept; // observers bool has_value() const noexcept; const type_info& type() const noexcept; }; } ``` cpp Standard library header <map> Standard library header <map> ============================= This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [map](../container/map "cpp/container/map") | collection of key-value pairs, sorted by keys, keys are unique (class template) | | [multimap](../container/multimap "cpp/container/multimap") | collection of key-value pairs, sorted by keys (class template) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/map/operator_cmp "cpp/container/map/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the map (function template) | | [std::swap(std::map)](../container/map/swap2 "cpp/container/map/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::map)](../container/map/erase_if "cpp/container/map/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/multimap/operator_cmp "cpp/container/multimap/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the multimap (function template) | | [std::swap(std::multimap)](../container/multimap/swap2 "cpp/container/multimap/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::multimap)](../container/multimap/erase_if "cpp/container/multimap/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template map template<class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> class map; template<class Key, class T, class Compare, class Allocator> bool operator==(const map<Key, T, Compare, Allocator>& x, const map<Key, T, Compare, Allocator>& y); template<class Key, class T, class Compare, class Allocator> /*synth-three-way-result*/<pair<const Key, T>> operator<=>(const map<Key, T, Compare, Allocator>& x, const map<Key, T, Compare, Allocator>& y); template<class Key, class T, class Compare, class Allocator> void swap(map<Key, T, Compare, Allocator>& x, map<Key, T, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class Key, class T, class Compare, class Allocator, class Predicate> typename map<Key, T, Compare, Allocator>::size_type erase_if(map<Key, T, Compare, Allocator>& c, Predicate pred); // class template multimap template<class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> class multimap; template<class Key, class T, class Compare, class Allocator> bool operator==(const multimap<Key, T, Compare, Allocator>& x, const multimap<Key, T, Compare, Allocator>& y); template<class Key, class T, class Compare, class Allocator> /*synth-three-way-result*/<pair<const Key, T>> operator<=>(const multimap<Key, T, Compare, Allocator>& x, const multimap<Key, T, Compare, Allocator>& y); template<class Key, class T, class Compare, class Allocator> void swap(multimap<Key, T, Compare, Allocator>& x, multimap<Key, T, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class Key, class T, class Compare, class Allocator, class Predicate> typename multimap<Key, T, Compare, Allocator>::size_type erase_if(multimap<Key, T, Compare, Allocator>& c, Predicate pred); namespace pmr { template<class Key, class T, class Compare = less<Key>> using map = std::map<Key, T, Compare, polymorphic_allocator<pair<const Key, T>>>; template<class Key, class T, class Compare = less<Key>> using multimap = std::multimap<Key, T, Compare, polymorphic_allocator<pair<const Key, T>>>; } } ``` #### Class template `[std::map](../container/map "cpp/container/map")` ``` namespace std { template<class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> class map { public: // types using key_type = Key; using mapped_type = T; using value_type = pair<const Key, T>; using key_compare = Compare; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using node_type = /* unspecified */; using insert_return_type = /*insert-return-type*/<iterator, node_type>; class value_compare { friend class map; protected: Compare comp; value_compare(Compare c) : comp(c) {} public: bool operator()(const value_type& x, const value_type& y) const { return comp(x.first, y.first); } }; // construct/copy/destroy map() : map(Compare()) { } explicit map(const Compare& comp, const Allocator& = Allocator()); template<class InputIt> map(InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& = Allocator()); map(const map& x); map(map&& x); explicit map(const Allocator&); map(const map&, const Allocator&); map(map&&, const Allocator&); map(initializer_list<value_type>, const Compare& = Compare(), const Allocator& = Allocator()); template<class InputIt> map(InputIt first, InputIt last, const Allocator& a) : map(first, last, Compare(), a) { } map(initializer_list<value_type> il, const Allocator& a) : map(il, Compare(), a) { } ~map(); map& operator=(const map& x); map& operator=(map&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Compare>); map& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // element access mapped_type& operator[](const key_type& x); mapped_type& operator[](key_type&& x); mapped_type& at(const key_type& x); const mapped_type& at(const key_type& x) const; // modifiers template<class... Args> pair<iterator, bool> emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); pair<iterator, bool> insert(const value_type& x); pair<iterator, bool> insert(value_type&& x); template<class P> pair<iterator, bool> insert(P&& x); iterator insert(const_iterator position, const value_type& x); iterator insert(const_iterator position, value_type&& x); template<class P> iterator insert(const_iterator position, P&&); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); insert_return_type insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); template<class... Args> pair<iterator, bool> try_emplace(const key_type& k, Args&&... args); template<class... Args> pair<iterator, bool> try_emplace(key_type&& k, Args&&... args); template<class... Args> iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args); template<class... Args> iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args); template<class M> pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj); template<class M> pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj); template<class M> iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj); template<class M> iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(map&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Compare>); void clear() noexcept; template<class C2> void merge(map<Key, T, C2, Allocator>& source); template<class C2> void merge(map<Key, T, C2, Allocator>&& source); template<class C2> void merge(multimap<Key, T, C2, Allocator>& source); template<class C2> void merge(multimap<Key, T, C2, Allocator>&& source); // observers key_compare key_comp() const; value_compare value_comp() const; // map operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; }; template<class InputIt, class Compare = less</*iter-key-type*/<InputIt>>, class Allocator = allocator</*iter-to-alloc-type*/<InputIt>>> map(InputIt, InputIt, Compare = Compare(), Allocator = Allocator()) -> map</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, Compare, Allocator>; template<class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> map(initializer_list<pair<Key, T>>, Compare = Compare(), Allocator = Allocator()) -> map<Key, T, Compare, Allocator>; template<class InputIt, class Allocator> map(InputIt, InputIt, Allocator) -> map</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, less</*iter-key-type*/<InputIt>>, Allocator>; template<class Key, class T, class Allocator> map(initializer_list<pair<Key, T>>, Allocator) -> map<Key, T, less<Key>, Allocator>; // swap template<class Key, class T, class Compare, class Allocator> void swap(map<Key, T, Compare, Allocator>& x, map<Key, T, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); } ``` #### Class template `[std::multimap](../container/multimap "cpp/container/multimap")` ``` namespace std { template<class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> class multimap { public: // types using key_type = Key; using mapped_type = T; using value_type = pair<const Key, T>; using key_compare = Compare; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using node_type = /* unspecified */; class value_compare { friend class multimap; protected: Compare comp; value_compare(Compare c) : comp(c) { } public: bool operator()(const value_type& x, const value_type& y) const { return comp(x.first, y.first); } }; // construct/copy/destroy multimap() : multimap(Compare()) { } explicit multimap(const Compare& comp, const Allocator& = Allocator()); template<class InputIt> multimap(InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& = Allocator()); multimap(const multimap& x); multimap(multimap&& x); explicit multimap(const Allocator&); multimap(const multimap&, const Allocator&); multimap(multimap&&, const Allocator&); multimap(initializer_list<value_type>, const Compare& = Compare(), const Allocator& = Allocator()); template<class InputIt> multimap(InputIt first, InputIt last, const Allocator& a) : multimap(first, last, Compare(), a) { } multimap(initializer_list<value_type> il, const Allocator& a) : multimap(il, Compare(), a) { } ~multimap(); multimap& operator=(const multimap& x); multimap& operator=(multimap&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Compare>); multimap& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> iterator emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& x); iterator insert(value_type&& x); template<class P> iterator insert(P&& x); iterator insert(const_iterator position, const value_type& x); iterator insert(const_iterator position, value_type&& x); template<class P> iterator insert(const_iterator position, P&& x); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); iterator insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(multimap&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Compare>); void clear() noexcept; template<class C2> void merge(multimap<Key, T, C2, Allocator>& source); template<class C2> void merge(multimap<Key, T, C2, Allocator>&& source); template<class C2> void merge(map<Key, T, C2, Allocator>& source); template<class C2> void merge(map<Key, T, C2, Allocator>&& source); // observers key_compare key_comp() const; value_compare value_comp() const; // map operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; }; template<class InputIt, class Compare = less</*iter-key-type*/<InputIt>>, class Allocator = allocator</*iter-to-alloc-type*/<InputIt>>> multimap(InputIt, InputIt, Compare = Compare(), Allocator = Allocator()) -> multimap</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, Compare, Allocator>; template<class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>>> multimap(initializer_list<pair<Key, T>>, Compare = Compare(), Allocator = Allocator()) -> multimap<Key, T, Compare, Allocator>; template<class InputIt, class Allocator> multimap(InputIt, InputIt, Allocator) -> multimap</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, less</*iter-key-type*/<InputIt>>, Allocator>; template<class Key, class T, class Allocator> multimap(initializer_list<pair<Key, T>>, Allocator) -> multimap<Key, T, less<Key>, Allocator>; // swap template<class Key, class T, class Compare, class Allocator> void swap(multimap<Key, T, Compare, Allocator>& x, multimap<Key, T, Compare, Allocator>& y) noexcept(noexcept(x.swap(y))); } ```
programming_docs
cpp Standard library header <numeric> Standard library header <numeric> ================================= This header is part of the [numeric](../numeric "cpp/numeric") library. | | | --- | | Functions | | [iota](../algorithm/iota "cpp/algorithm/iota") (C++11) | fills a range with successive increments of the starting value (function template) | | [ranges::iota](../algorithm/ranges/iota "cpp/algorithm/ranges/iota") (C++23) | fills a range with successive increments of the starting value (niebloid) | | [accumulate](../algorithm/accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [reduce](../algorithm/reduce "cpp/algorithm/reduce") (C++17) | similar to `[std::accumulate](../algorithm/accumulate "cpp/algorithm/accumulate")`, except out of order (function template) | | [transform\_reduce](../algorithm/transform_reduce "cpp/algorithm/transform reduce") (C++17) | applies an invocable, then reduces out of order (function template) | | [inner\_product](../algorithm/inner_product "cpp/algorithm/inner product") | computes the inner product of two ranges of elements (function template) | | [adjacent\_difference](../algorithm/adjacent_difference "cpp/algorithm/adjacent difference") | computes the differences between adjacent elements in a range (function template) | | [partial\_sum](../algorithm/partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [inclusive\_scan](../algorithm/inclusive_scan "cpp/algorithm/inclusive scan") (C++17) | similar to `[std::partial\_sum](../algorithm/partial_sum "cpp/algorithm/partial sum")`, includes the ith input element in the ith sum (function template) | | [exclusive\_scan](../algorithm/exclusive_scan "cpp/algorithm/exclusive scan") (C++17) | similar to `[std::partial\_sum](../algorithm/partial_sum "cpp/algorithm/partial sum")`, excludes the ith input element from the ith sum (function template) | | [transform\_inclusive\_scan](../algorithm/transform_inclusive_scan "cpp/algorithm/transform inclusive scan") (C++17) | applies an invocable, then calculates inclusive scan (function template) | | [transform\_exclusive\_scan](../algorithm/transform_exclusive_scan "cpp/algorithm/transform exclusive scan") (C++17) | applies an invocable, then calculates exclusive scan (function template) | | [gcd](../numeric/gcd "cpp/numeric/gcd") (C++17) | `constexpr` function template returning the greatest common divisor of two integers (function template) | | [lcm](../numeric/lcm "cpp/numeric/lcm") (C++17) | `constexpr` function template returning the least common multiple of two integers (function template) | | [midpoint](../numeric/midpoint "cpp/numeric/midpoint") (C++20) | midpoint between two numbers or pointers (function template) | ### Synopsis ``` namespace std { // accumulate template<class InputIt, class T> constexpr T accumulate(InputIt first, InputIt last, T init); template<class InputIt, class T, class BinaryOperation> constexpr T accumulate(InputIt first, InputIt last, T init, BinaryOperation binary_op); // reduce template<class InputIt> constexpr typename iterator_traits<InputIt>::value_type reduce(InputIt first, InputIt last); template<class InputIt, class T> constexpr T reduce(InputIt first, InputIt last, T init); template<class InputIt, class T, class BinaryOperation> constexpr T reduce(InputIt first, InputIt last, T init, BinaryOperation binary_op); template<class ExecutionPolicy, class ForwardIt> typename iterator_traits<ForwardIt>::value_type reduce(ExecutionPolicy&& exec, ForwardIt first, ForwardIt last); template<class ExecutionPolicy, class ForwardIt, class T> T reduce(ExecutionPolicy&& exec, ForwardIt first, ForwardIt last, T init); template<class ExecutionPolicy, class ForwardIt, class T, class BinaryOperation> T reduce(ExecutionPolicy&& exec, ForwardIt first, ForwardIt last, T init, BinaryOperation binary_op); // inner product template<class InputIt1, class InputIt2, class T> constexpr T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init); template<class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2> constexpr T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); // transform reduce template<class InputIt1, class InputIt2, class T> constexpr T transform_reduce(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init); template<class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2> constexpr T transform_reduce(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); template<class InputIt, class T, class BinaryOperation, class UnaryOperation> constexpr T transform_reduce(InputIt first, InputIt last, T init, BinaryOperation binary_op, UnaryOperation unary_op); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T> T transform_reduce(ExecutionPolicy&& exec, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, T init); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, class BinaryOperation1, class BinaryOperation2> T transform_reduce(ExecutionPolicy&& exec, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); template<class ExecutionPolicy, class ForwardIt, class T, class BinaryOperation, class UnaryOperation> T transform_reduce(ExecutionPolicy&& exec, ForwardIt first, ForwardIt last, T init, BinaryOperation binary_op, UnaryOperation unary_op); // partial sum template<class InputIt, class OutputIt> constexpr OutputIt partial_sum(InputIt first, InputIt last, OutputIt result); template<class InputIt, class OutputIt, class BinaryOperation> constexpr OutputIt partial_sum(InputIt first, InputIt last, OutputIt result, BinaryOperation binary_op); // exclusive scan template<class InputIt, class OutputIt, class T> constexpr OutputIt exclusive_scan(InputIt first, InputIt last, OutputIt result, T init); template<class InputIt, class OutputIt, class T, class BinaryOperation> constexpr OutputIt exclusive_scan(InputIt first, InputIt last, OutputIt result, T init, BinaryOperation binary_op); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T> ForwardIt2 exclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, T init); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, class BinaryOperation> ForwardIt2 exclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, T init, BinaryOperation binary_op); // inclusive scan template<class InputIt, class OutputIt> constexpr OutputIt inclusive_scan(InputIt first, InputIt last, OutputIt result); template<class InputIt, class OutputIt, class BinaryOperation> constexpr OutputIt inclusive_scan(InputIt first, InputIt last, OutputIt result, BinaryOperation binary_op); template<class InputIt, class OutputIt, class BinaryOperation, class T> constexpr OutputIt inclusive_scan(InputIt first, InputIt last, OutputIt result, BinaryOperation binary_op, T init); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2> ForwardIt2 inclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation> ForwardIt2 inclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, BinaryOperation binary_op); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation, class T> ForwardIt2 inclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, BinaryOperation binary_op, T init); // transform exclusive scan template<class InputIt, class OutputIt, class T, class BinaryOperation, class UnaryOperation> constexpr OutputIt transform_exclusive_scan(InputIt first, InputIt last, OutputIt result, T init, BinaryOperation binary_op, UnaryOperation unary_op); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, class BinaryOperation, class UnaryOperation> ForwardIt2 transform_exclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, T init, BinaryOperation binary_op, UnaryOperation unary_op); // transform inclusive scan template<class InputIt, class OutputIt, class BinaryOperation, class UnaryOperation> constexpr OutputIt transform_inclusive_scan(InputIt first, InputIt last, OutputIt result, BinaryOperation binary_op, UnaryOperation unary_op); template<class InputIt, class OutputIt, class BinaryOperation, class UnaryOperation, class T> constexpr OutputIt transform_inclusive_scan(InputIt first, InputIt last, OutputIt result, BinaryOperation binary_op, UnaryOperation unary_op, T init); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation, class UnaryOperation> ForwardIt2 transform_inclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, BinaryOperation binary_op, UnaryOperation unary_op); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation, class UnaryOperation, class T> ForwardIt2 transform_inclusive_scan(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, BinaryOperation binary_op, UnaryOperation unary_op, T init); // adjacent difference template<class InputIt, class OutputIt> constexpr OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt result); template<class InputIt, class OutputIt, class BinaryOperation> constexpr OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt result, BinaryOperation binary_op); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2> ForwardIt2 adjacent_difference(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result); template<class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation> ForwardIt2 adjacent_difference(ExecutionPolicy&& exec, ForwardIt1 first, ForwardIt1 last, ForwardIt2 result, BinaryOperation binary_op); // iota template<class ForwardIt, class T> constexpr void iota(ForwardIt first, ForwardIt last, T value); namespace ranges { template<class O, class T> using iota_result = out_value_result<O, T>; template<input_or_output_iterator O, sentinel_for<O> S, weakly_incrementable T> requires indirectly_writable<O, const T&> constexpr iota_result<O, T> iota(O first, S last, T value); template<weakly_incrementable T, output_range<const T&> R> constexpr iota_result<borrowed_iterator_t<R>, T> iota(R&& r, T value); } // greatest common divisor template<class M, class N> constexpr common_type_t<M, N> gcd(M m, N n); // least common multiple template<class M, class N> constexpr common_type_t<M, N> lcm(M m, N n); // midpoint template<class T> constexpr T midpoint(T a, T b) noexcept; template<class T> constexpr T* midpoint(T* a, T* b); } ``` cpp Standard library header <regex> (C++11) Standard library header <regex> (C++11) ======================================= This header is part of the [regular expressions](../regex "cpp/regex") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [basic\_regex](../regex/basic_regex "cpp/regex/basic regex") (C++11) | regular expression object (class template) | | `[std::regex](../regex/basic_regex "cpp/regex/basic regex")` | [std::basic\_regex](http://en.cppreference.com/w/cpp/regex/basic_regex)<char> (typedef) | | `[std::wregex](../regex/basic_regex "cpp/regex/basic regex")` | [std::basic\_regex](http://en.cppreference.com/w/cpp/regex/basic_regex)<wchar\_t> (typedef) | | [sub\_match](../regex/sub_match "cpp/regex/sub match") (C++11) | identifies the sequence of characters matched by a sub-expression (class template) | | `[std::csub\_match](../regex/sub_match "cpp/regex/sub match")` | [std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<const char\*> (typedef) | | `[std::wcsub\_match](../regex/sub_match "cpp/regex/sub match")` | [std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<const wchar\_t\*> (typedef) | | `[std::ssub\_match](../regex/sub_match "cpp/regex/sub match")` | [std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<std::string::const\_iterator> (typedef) | | `[std::wssub\_match](../regex/sub_match "cpp/regex/sub match")` | [std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<std::wstring::const\_iterator> (typedef) | | [match\_results](../regex/match_results "cpp/regex/match results") (C++11) | identifies one regular expression match, including all sub-expression matches (class template) | | `[std::cmatch](../regex/match_results "cpp/regex/match results")` | [std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<const char\*> (typedef) | | `[std::wcmatch](../regex/match_results "cpp/regex/match results")` | [std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<const wchar\_t\*> (typedef) | | `[std::smatch](../regex/match_results "cpp/regex/match results")` | [std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<std::string::const\_iterator> (typedef) | | `[std::wsmatch](../regex/match_results "cpp/regex/match results")` | [std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<std::wstring::const\_iterator> (typedef) | | [regex\_iterator](../regex/regex_iterator "cpp/regex/regex iterator") (C++11) | iterates through all regex matches within a character sequence (class template) | | `[std::cregex\_iterator](../regex/regex_iterator "cpp/regex/regex iterator")` | [std::regex\_iterator](http://en.cppreference.com/w/cpp/regex/regex_iterator)<const char\*> (typedef) | | `[std::wcregex\_iterator](../regex/regex_iterator "cpp/regex/regex iterator")` | [std::regex\_iterator](http://en.cppreference.com/w/cpp/regex/regex_iterator)<const wchar\_t\*> (typedef) | | `[std::sregex\_iterator](../regex/regex_iterator "cpp/regex/regex iterator")` | [std::regex\_iterator](http://en.cppreference.com/w/cpp/regex/regex_iterator)<std::string::const\_iterator> (typedef) | | `[std::wsregex\_iterator](../regex/regex_iterator "cpp/regex/regex iterator")` | [std::regex\_iterator](http://en.cppreference.com/w/cpp/regex/regex_iterator)<std::wstring::const\_iterator> (typedef) | | [regex\_token\_iterator](../regex/regex_token_iterator "cpp/regex/regex token iterator") (C++11) | iterates through the specified sub-expressions within all regex matches in a given string or through unmatched substrings (class template) | | `[std::cregex\_token\_iterator](../regex/regex_token_iterator "cpp/regex/regex token iterator")` | [std::regex\_token\_iterator](http://en.cppreference.com/w/cpp/regex/regex_token_iterator)<const char\*> (typedef) | | `[std::wcregex\_token\_iterator](../regex/regex_token_iterator "cpp/regex/regex token iterator")` | [std::regex\_token\_iterator](http://en.cppreference.com/w/cpp/regex/regex_token_iterator)<const wchar\_t\*> (typedef) | | `[std::sregex\_token\_iterator](../regex/regex_token_iterator "cpp/regex/regex token iterator")` | [std::regex\_token\_iterator](http://en.cppreference.com/w/cpp/regex/regex_token_iterator)<std::string::const\_iterator> (typedef) | | `[std::wsregex\_token\_iterator](../regex/regex_token_iterator "cpp/regex/regex token iterator")` | [std::regex\_token\_iterator](http://en.cppreference.com/w/cpp/regex/regex_token_iterator)<std::wstring::const\_iterator> (typedef) | | [regex\_error](../regex/regex_error "cpp/regex/regex error") (C++11) | reports errors generated by the regular expressions library (class) | | [regex\_traits](../regex/regex_traits "cpp/regex/regex traits") (C++11) | provides metainformation about a character type, required by the regex library (class template) | | regex constant types | | Defined in namespace `std::regex_constants` | | [syntax\_option\_type](../regex/syntax_option_type "cpp/regex/syntax option type") (C++11) | general options controlling regex behavior (typedef) | | [match\_flag\_type](../regex/match_flag_type "cpp/regex/match flag type") (C++11) | options specific to matching (typedef) | | [error\_type](../regex/error_type "cpp/regex/error type") (C++11) | describes different types of matching errors (typedef) | | Functions | | Algorithm | | [regex\_match](../regex/regex_match "cpp/regex/regex match") (C++11) | attempts to match a regular expression to an entire character sequence (function template) | | [regex\_search](../regex/regex_search "cpp/regex/regex search") (C++11) | attempts to match a regular expression to any part of a character sequence (function template) | | [regex\_replace](../regex/regex_replace "cpp/regex/regex replace") (C++11) | replaces occurrences of a regular expression with formatted replacement text (function template) | | Non-member operations | | [std::swap(std::basic\_regex)](../regex/basic_regex/swap2 "cpp/regex/basic regex/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../regex/sub_match/operator_cmp "cpp/regex/sub match/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares a `sub_match` with another `sub_match`, a string, or a character (function template) | | [operator<<](../regex/sub_match/operator_ltlt "cpp/regex/sub match/operator ltlt") | outputs the matched character subsequence (function template) | | [operator==operator!=](../regex/match_results/operator_cmp "cpp/regex/match results/operator cmp") (removed in C++20) | lexicographically compares the values in the two match result (function template) | | [std::swap(std::match\_results)](../regex/match_results/swap2 "cpp/regex/match results/swap2") (C++11) | specializes the [`std::swap`](../algorithm/swap "cpp/algorithm/swap") algorithm (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // regex constants namespace regex_constants { using syntax_option_type = /*T1*/; using match_flag_type = /*T2*/; using error_type = /*T3*/; } // class regex_error class regex_error; // class template regex_traits template<class CharT> struct regex_traits; // class template basic_regex template<class CharT, class Traits = regex_traits<CharT>> class basic_regex; using regex = basic_regex<char>; using wregex = basic_regex<wchar_t>; // basic_regex swap template<class CharT, class Traits> void swap(basic_regex<CharT, Traits>& e1, basic_regex<CharT, Traits>& e2); // class template sub_match template<class BiIt> class sub_match; using csub_match = sub_match<const char*>; using wcsub_match = sub_match<const wchar_t*>; using ssub_match = sub_match<string::const_iterator>; using wssub_match = sub_match<wstring::const_iterator>; // sub_match non-member operators template<class BiIt> bool operator==(const sub_match<BiIt>& lhs, const sub_match<BiIt>& rhs); template<class BiIt> auto operator<=>(const sub_match<BiIt>& lhs, const sub_match<BiIt>& rhs); template<class BiIt, class ST, class SA> bool operator==( const sub_match<BiIt>& lhs, const basic_string<typename iterator_traits<BiIt>::value_type, ST, SA>& rhs); template<class BiIt, class ST, class SA> auto operator<=>( const sub_match<BiIt>& lhs, const basic_string<typename iterator_traits<BiIt>::value_type, ST, SA>& rhs); template<class BiIt> bool operator==(const sub_match<BiIt>& lhs, const typename iterator_traits<BiIt>::value_type* rhs); template<class BiIt> auto operator<=>(const sub_match<BiIt>& lhs, const typename iterator_traits<BiIt>::value_type* rhs); template<class BiIt> bool operator==(const sub_match<BiIt>& lhs, const typename iterator_traits<BiIt>::value_type& rhs); template<class BiIt> auto operator<=>(const sub_match<BiIt>& lhs, const typename iterator_traits<BiIt>::value_type& rhs); template<class CharT, class ST, class BiIt> basic_ostream<CharT, ST>& operator<<(basic_ostream<CharT, ST>& os, const sub_match<BiIt>& m); // class template match_results template<class BiIt, class Allocator = allocator<sub_match<BiIt>>> class match_results; using cmatch = match_results<const char*>; using wcmatch = match_results<const wchar_t*>; using smatch = match_results<string::const_iterator>; using wsmatch = match_results<wstring::const_iterator>; // match_results comparisons template<class BiIt, class Allocator> bool operator==(const match_results<BiIt, Allocator>& m1, const match_results<BiIt, Allocator>& m2); // match_results swap template<class BiIt, class Allocator> void swap(match_results<BiIt, Allocator>& m1, match_results<BiIt, Allocator>& m2); // function template regex_match template<class BiIt, class Allocator, class CharT, class Traits> bool regex_match(BiIt first, BiIt last, match_results<BiIt, Allocator>& m, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class BiIt, class CharT, class Traits> bool regex_match(BiIt first, BiIt last, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class CharT, class Allocator, class Traits> bool regex_match(const CharT* str, match_results<const CharT*, Allocator>& m, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class ST, class SA, class Allocator, class CharT, class Traits> bool regex_match(const basic_string<CharT, ST, SA>& s, match_results<typename basic_string<CharT, ST, SA>::const_iterator, Allocator>& m, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class ST, class SA, class Allocator, class CharT, class Traits> bool regex_match(const basic_string<CharT, ST, SA>&&, match_results<typename basic_string<CharT, ST, SA>::const_iterator, Allocator>&, const basic_regex<CharT, Traits>&, regex_constants::match_flag_type = regex_constants::match_default) = delete; template<class CharT, class Traits> bool regex_match(const CharT* str, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class ST, class SA, class CharT, class Traits> bool regex_match(const basic_string<CharT, ST, SA>& s, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); // function template regex_search template<class BiIt, class Allocator, class CharT, class Traits> bool regex_search(BiIt first, BiIt last, match_results<BiIt, Allocator>& m, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class BiIt, class CharT, class Traits> bool regex_search(BiItfirst, BiIt last, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class CharT, class Allocator, class Traits> bool regex_search(const CharT* str, match_results<const CharT*, Allocator>& m, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class CharT, class Traits> bool regex_search(const CharT* str, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class ST, class SA, class CharT, class Traits> bool regex_search(const basic_string<CharT, ST, SA>& s, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class ST, class SA, class Allocator, class CharT, class Traits> bool regex_search(const basic_string<CharT, ST, SA>& s, match_results<typename basic_string<CharT, ST, SA>::const_iterator, Allocator>& m, const basic_regex<CharT, Traits>& e, regex_constants::match_flag_type flags = regex_constants::match_default); template<class ST, class SA, class Allocator, class CharT, class Traits> bool regex_search(const basic_string<CharT, ST, SA>&&, match_results<typename basic_string<CharT, ST, SA>::const_iterator, Allocator>&, const basic_regex<CharT, Traits>&, regex_constants::match_flag_type = regex_constants::match_default) = delete; // function template regex_replace template<class OutputIt, class BiIt, class Traits, class CharT, class ST, class SA> OutputIt regex_replace(OutputIt out, BiIt first, BiIt last, const basic_regex<CharT, Traits>& e, const basic_string<CharT, ST, SA>& fmt, regex_constants::match_flag_type flags = regex_constants::match_default); template<class OutputIt, class BiIt, class Traits, class CharT> OutputIt regex_replace(OutputIt out, BiIt first, BiIt last, const basic_regex<CharT, Traits>& e, const CharT* fmt, regex_constants::match_flag_type flags = regex_constants::match_default); template<class Traits, class CharT, class ST, class SA, class FST, class FSA> basic_string<CharT, ST, SA> regex_replace(const basic_string<CharT, ST, SA>& s, const basic_regex<CharT, Traits>& e, const basic_string<CharT, FST, FSA>& fmt, regex_constants::match_flag_type flags = regex_constants::match_default); template<class Traits, class CharT, class ST, class SA> basic_string<CharT, ST, SA> regex_replace(const basic_string<CharT, ST, SA>& s, const basic_regex<CharT, Traits>& e, const CharT* fmt, regex_constants::match_flag_type flags = regex_constants::match_default); template<class Traits, class CharT, class ST, class SA> basic_string<CharT> regex_replace(const CharT* s, const basic_regex<CharT, Traits>& e, const basic_string<CharT, ST, SA>& fmt, regex_constants::match_flag_type flags = regex_constants::match_default); template<class Traits, class CharT> basic_string<CharT> regex_replace(const CharT* s, const basic_regex<CharT, Traits>& e, const CharT* fmt, regex_constants::match_flag_type flags = regex_constants::match_default); // class template regex_iterator template<class BiIt, class CharT = typename iterator_traits<BiIt>::value_type, class Traits = regex_traits<CharT>> class regex_iterator; using cregex_iterator = regex_iterator<const char*>; using wcregex_iterator = regex_iterator<const wchar_t*>; using sregex_iterator = regex_iterator<string::const_iterator>; using wsregex_iterator = regex_iterator<wstring::const_iterator>; // class template regex_token_iterator template<class BiIt, class CharT = typename iterator_traits<BiIt>::value_type, class Traits = regex_traits<CharT>> class regex_token_iterator; using cregex_token_iterator = regex_token_iterator<const char*>; using wcregex_token_iterator = regex_token_iterator<const wchar_t*>; using sregex_token_iterator = regex_token_iterator<string::const_iterator>; using wsregex_token_iterator = regex_token_iterator<wstring::const_iterator>; namespace pmr { template<class BiIt> using match_results = std::match_results<BiIt, polymorphic_allocator<sub_match<BiIt>>>; using cmatch = match_results<const char*>; using wcmatch = match_results<const wchar_t*>; using smatch = match_results<string::const_iterator>; using wsmatch = match_results<wstring::const_iterator>; } } ``` #### Bitmask type `[std::regex\_constants::syntax\_option\_type](../regex/syntax_option_type "cpp/regex/syntax option type")` ``` namespace std::regex_constants { using syntax_option_type = /*T1*/; inline constexpr syntax_option_type icase = /* unspecified */; inline constexpr syntax_option_type nosubs = /* unspecified */; inline constexpr syntax_option_type optimize = /* unspecified */; inline constexpr syntax_option_type collate = /* unspecified */; inline constexpr syntax_option_type ECMAScript = /* unspecified */; inline constexpr syntax_option_type basic = /* unspecified */; inline constexpr syntax_option_type extended = /* unspecified */; inline constexpr syntax_option_type awk = /* unspecified */; inline constexpr syntax_option_type grep = /* unspecified */; inline constexpr syntax_option_type egrep = /* unspecified */; inline constexpr syntax_option_type multiline = /* unspecified */; } ``` #### Bitmask type `[std::regex\_constants::match\_flag\_type](../regex/match_flag_type "cpp/regex/match flag type")` ``` namespace std::regex_constants { using match_flag_type = /*T2*/; inline constexpr match_flag_type match_default = {}; inline constexpr match_flag_type match_not_bol = /* unspecified */; inline constexpr match_flag_type match_not_eol = /* unspecified */; inline constexpr match_flag_type match_not_bow = /* unspecified */; inline constexpr match_flag_type match_not_eow = /* unspecified */; inline constexpr match_flag_type match_any = /* unspecified */; inline constexpr match_flag_type match_not_null = /* unspecified */; inline constexpr match_flag_type match_continuous = /* unspecified */; inline constexpr match_flag_type match_prev_avail = /* unspecified */; inline constexpr match_flag_type format_default = {}; inline constexpr match_flag_type format_sed = /* unspecified */; inline constexpr match_flag_type format_no_copy = /* unspecified */; inline constexpr match_flag_type format_first_only = /* unspecified */; } ``` #### Enumerated type `[std::regex\_constants::error\_type](../regex/error_type "cpp/regex/error type")` ``` namespace std::regex_constants { using error_type = /*T3*/; inline constexpr error_type error_collate = /* unspecified */; inline constexpr error_type error_ctype = /* unspecified */; inline constexpr error_type error_escape = /* unspecified */; inline constexpr error_type error_backref = /* unspecified */; inline constexpr error_type error_brack = /* unspecified */; inline constexpr error_type error_paren = /* unspecified */; inline constexpr error_type error_brace = /* unspecified */; inline constexpr error_type error_badbrace = /* unspecified */; inline constexpr error_type error_range = /* unspecified */; inline constexpr error_type error_space = /* unspecified */; inline constexpr error_type error_badrepeat = /* unspecified */; inline constexpr error_type error_complexity = /* unspecified */; inline constexpr error_type error_stack = /* unspecified */; } ``` #### Class `[std::regex\_error](../regex/regex_error "cpp/regex/regex error")` ``` namespace std { class regex_error : public runtime_error { public: explicit regex_error(regex_constants::error_type ecode); regex_constants::error_type code() const; }; } ``` #### Class template `[std::regex\_traits](../regex/regex_traits "cpp/regex/regex traits")` ``` namespace std { template<class CharT> struct regex_traits { using char_type = CharT; using string_type = basic_string<char_type>; using locale_type = locale; using char_class_type = /* bitmask-type */; regex_traits(); static size_t length(const char_type* p); CharT translate(CharT c) const; CharT translate_nocase(CharT c) const; template<class ForwardIt> string_type transform(ForwardIt first, ForwardIt last) const; template<class ForwardIt> string_type transform_primary(ForwardIt first, ForwardIt last) const; template<class ForwardIt> string_type lookup_collatename(ForwardIt first, ForwardIt last) const; template<class ForwardIt> char_class_type lookup_classname(ForwardIt first, ForwardIt last, bool icase = false) const; bool isctype(CharT c, char_class_type f) const; int value(CharT ch, int radix) const; locale_type imbue(locale_type l); locale_type getloc() const; }; } ``` #### Class template `[std::basic\_regex](../regex/basic_regex "cpp/regex/basic regex")` ``` namespace std { template<class CharT, class Traits = regex_traits<CharT>> class basic_regex { public: // types using value_type = CharT; using Traits_type = Traits; using string_type = typename Traits::string_type; using flag_type = regex_constants::syntax_option_type; using locale_type = typename Traits::locale_type; // constants static constexpr flag_type icase = regex_constants::icase; static constexpr flag_type nosubs = regex_constants::nosubs; static constexpr flag_type optimize = regex_constants::optimize; static constexpr flag_type collate = regex_constants::collate; static constexpr flag_type ECMAScript = regex_constants::ECMAScript; static constexpr flag_type basic = regex_constants::basic; static constexpr flag_type extended = regex_constants::extended; static constexpr flag_type awk = regex_constants::awk; static constexpr flag_type grep = regex_constants::grep; static constexpr flag_type egrep = regex_constants::egrep; static constexpr flag_type multiline = regex_constants::multiline; // construct/copy/destroy basic_regex(); explicit basic_regex(const CharT* p, flag_type f = regex_constants::ECMAScript); basic_regex(const CharT* p, size_t len, flag_type f = regex_constants::ECMAScript); basic_regex(const basic_regex&); basic_regex(basic_regex&&) noexcept; template<class ST, class SA> explicit basic_regex(const basic_string<CharT, ST, SA>& s, flag_type f = regex_constants::ECMAScript); template<class ForwardIt> basic_regex(ForwardIt first, ForwardIt last, flag_type f = regex_constants::ECMAScript); basic_regex(initializer_list<CharT> il, flag_type f = regex_constants::ECMAScript); ~basic_regex(); // assign basic_regex& operator=(const basic_regex& e); basic_regex& operator=(basic_regex&& e) noexcept; basic_regex& operator=(const CharT* p); basic_regex& operator=(initializer_list<CharT> il); template<class ST, class SA> basic_regex& operator=(const basic_string<CharT, ST, SA>& s); basic_regex& assign(const basic_regex& e); basic_regex& assign(basic_regex&& e) noexcept; basic_regex& assign(const CharT* p, flag_type f = regex_constants::ECMAScript); basic_regex& assign(const CharT* p, size_t len, flag_type f = regex_constants::ECMAScript); template<class ST, class SA> basic_regex& assign(const basic_string<CharT, ST, SA>& s, flag_type f = regex_constants::ECMAScript); template<class InputIt> basic_regex& assign(InputIt first, InputIt last, flag_type f = regex_constants::ECMAScript); basic_regex& assign(initializer_list<CharT>, flag_type f = regex_constants::ECMAScript); // const operations unsigned mark_count() const; flag_type flags() const; // locale locale_type imbue(locale_type loc); locale_type getloc() const; // swap void swap(basic_regex&); }; template<class ForwardIt> basic_regex(ForwardIt, ForwardIt, regex_constants::syntax_option_type = regex_constants::ECMAScript) -> basic_regex<typename iterator_traits<ForwardIt>::value_type>; } ``` #### Class template `[std::sub\_match](../regex/sub_match "cpp/regex/sub match")` ``` namespace std { template<class BiIt> class sub_match : public pair<BiIt, BiIt> { public: using value_type = typename iterator_traits<BiIt>::value_type; using difference_type = typename iterator_traits<BiIt>::difference_type; using iterator = BiIt; using string_type = basic_string<value_type>; bool matched; constexpr sub_match(); difference_type length() const; operator string_type() const; string_type str() const; int compare(const sub_match& s) const; int compare(const string_type& s) const; int compare(const value_type* s) const; }; } ``` #### Class template `[std::match\_results](../regex/match_results "cpp/regex/match results")` ``` namespace std { template<class BiIt, class Allocator = allocator<sub_match<BiIt>>> class match_results { public: using value_type = sub_match<BiIt>; using const_reference = const value_type&; using reference = value_type&; using const_iterator = /* implementation-defined */; using iterator = const_iterator; using difference_type = typename iterator_traits<BiIt>::difference_type; using size_type = typename allocator_traits<Allocator>::size_type; using allocator_type = Allocator; using char_type = typename iterator_traits<BiIt>::value_type; using string_type = basic_string<char_type>; // construct/copy/destroy match_results() : match_results(Allocator()) {} explicit match_results(const Allocator&); match_results(const match_results& m); match_results(match_results&& m) noexcept; match_results& operator=(const match_results& m); match_results& operator=(match_results&& m); ~match_results(); // state bool ready() const; // size size_type size() const; size_type max_size() const; [[nodiscard]] bool empty() const; // element access difference_type length(size_type sub = 0) const; difference_type position(size_type sub = 0) const; string_type str(size_type sub = 0) const; const_reference operator[](size_type n) const; const_reference prefix() const; const_reference suffix() const; const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; // format template<class OutputIt> OutputIt format(OutputIt out, const char_type* fmt_first, const char_type* fmt_last, regex_constants::match_flag_type flags = regex_constants::format_default) const; template<class OutputIt, class ST, class SA> OutputIt format(OutputIt out, const basic_string<char_type, ST, SA>& fmt, regex_constants::match_flag_type flags = regex_constants::format_default) const; template<class ST, class SA> basic_string<char_type, ST, SA> format(const basic_string<char_type, ST, SA>& fmt, regex_constants::match_flag_type flags = regex_constants::format_default) const; string_type format(const char_type* fmt, regex_constants::match_flag_type flags = regex_constants::format_default) const; // allocator allocator_type get_allocator() const; // swap void swap(match_results& that); }; } ```
programming_docs
cpp Standard library header <forward_list> (C++11) Standard library header <forward\_list> (C++11) =============================================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [forward\_list](../container/forward_list "cpp/container/forward list") (C++11) | singly-linked list (class template) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/forward_list/operator_cmp "cpp/container/forward list/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the forward\_list (function template) | | [std::swap(std::forward\_list)](../container/forward_list/swap2 "cpp/container/forward list/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::forward\_list)erase\_if(std::forward\_list)](../container/forward_list/erase2 "cpp/container/forward list/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template forward_list template<class T, class Allocator = allocator<T>> class forward_list; template<class T, class Allocator> bool operator==(const forward_list<T, Allocator>& x, const forward_list<T, Allocator>& y); template<class T, class Allocator> /*synth-three-way-result*/<T> operator<=>(const forward_list<T, Allocator>& x, const forward_list<T, Allocator>& y); template<class T, class Allocator> void swap(forward_list<T, Allocator>& x, forward_list<T, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class T, class Allocator, class U> typename forward_list<T, Allocator>::size_type erase(forward_list<T, Allocator>& c, const U& value); template<class T, class Allocator, class Predicate> typename forward_list<T, Allocator>::size_type erase_if(forward_list<T, Allocator>& c, Predicate pred); namespace pmr { template<class T> using forward_list = std::forward_list<T, polymorphic_allocator<T>>; } } ``` #### Class template `[std::forward\_list](../container/forward_list "cpp/container/forward list")` ``` namespace std { template<class T, class Allocator = allocator<T>> class forward_list { public: // types using value_type = T; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; // construct/copy/destroy forward_list() : forward_list(Allocator()) { } explicit forward_list(const Allocator&); explicit forward_list(size_type n, const Allocator& = Allocator()); forward_list(size_type n, const T& value, const Allocator& = Allocator()); template<class InputIt> forward_list(InputIt first, InputIt last, const Allocator& = Allocator()); forward_list(const forward_list& x); forward_list(forward_list&& x); forward_list(const forward_list& x, const Allocator&); forward_list(forward_list&& x, const Allocator&); forward_list(initializer_list<T>, const Allocator& = Allocator()); ~forward_list(); forward_list& operator=(const forward_list& x); forward_list& operator=(forward_list&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value); forward_list& operator=(initializer_list<T>); template<class InputIt> void assign(InputIt first, InputIt last); void assign(size_type n, const T& t); void assign(initializer_list<T>); allocator_type get_allocator() const noexcept; // iterators iterator before_begin() noexcept; const_iterator before_begin() const noexcept; iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cbefore_begin() const noexcept; const_iterator cend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type max_size() const noexcept; // element access reference front(); const_reference front() const; // modifiers template<class... Args> reference emplace_front(Args&&... args); void push_front(const T& x); void push_front(T&& x); void pop_front(); template<class... Args> iterator emplace_after(const_iterator position, Args&&... args); iterator insert_after(const_iterator position, const T& x); iterator insert_after(const_iterator position, T&& x); iterator insert_after(const_iterator position, size_type n, const T& x); template<class InputIt> iterator insert_after(const_iterator position, InputIt first, InputIt last); iterator insert_after(const_iterator position, initializer_list<T> il); iterator erase_after(const_iterator position); iterator erase_after(const_iterator position, const_iterator last); void swap(forward_list&) noexcept(allocator_traits<Allocator>::is_always_equal::value); void resize(size_type sz); void resize(size_type sz, const value_type& c); void clear() noexcept; // forward_list operations void splice_after(const_iterator position, forward_list& x); void splice_after(const_iterator position, forward_list&& x); void splice_after(const_iterator position, forward_list& x, const_iterator i); void splice_after(const_iterator position, forward_list&& x, const_iterator i); void splice_after(const_iterator position, forward_list& x, const_iterator first, const_iterator last); void splice_after(const_iterator position, forward_list&& x, const_iterator first, const_iterator last); size_type remove(const T& value); template<class Predicate> size_type remove_if(Predicate pred); size_type unique(); template<class BinaryPredicate> size_type unique(BinaryPredicate binary_pred); void merge(forward_list& x); void merge(forward_list&& x); template<class Compare> void merge(forward_list& x, Compare comp); template<class Compare> void merge(forward_list&& x, Compare comp); void sort(); template<class Compare> void sort(Compare comp); void reverse() noexcept; }; template<class InputIt, class Allocator = allocator</*iter-value-type*/<InputIt>>> forward_list(InputIt, InputIt, Allocator = Allocator()) -> forward_list</*iter-value-type*/<InputIt>, Allocator>; // swap template<class T, class Allocator> void swap(forward_list<T, Allocator>& x, forward_list<T, Allocator>& y) noexcept(noexcept(x.swap(y))); } ``` cpp Standard library header <execution> (C++17) Standard library header <execution> (C++17) =========================================== This header is part of the [algorithm](../algorithm "cpp/algorithm") library. | | | --- | | Classes | | [is\_execution\_policy](../algorithm/is_execution_policy "cpp/algorithm/is execution policy") (C++17) | test whether a class represents an execution policy (class template) | | Defined in namespace `std::execution` | | [sequenced\_policyparallel\_policyparallel\_unsequenced\_policyunsequenced\_policy](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") (C++17)(C++17)(C++17)(C++20) | execution policy types (class) | | Constants | | Defined in namespace `std::execution` | | [seqparpar\_unsequnseq](../algorithm/execution_policy_tag "cpp/algorithm/execution policy tag") (C++17)(C++17)(C++17)(C++20) | global execution policy objects (constant) | ### Synopsis ``` namespace std { // execution policy type trait template<class T> struct is_execution_policy; template<class T> inline constexpr bool is_execution_policy_v = is_execution_policy<T>::value; } namespace std::execution { // sequenced execution policy class sequenced_policy; // parallel execution policy class parallel_policy; // parallel and unsequenced execution policy class parallel_unsequenced_policy; // unsequenced execution policy class unsequenced_policy; // execution policy objects inline constexpr sequenced_policy seq{ /*unspecified*/ }; inline constexpr parallel_policy par{ /*unspecified*/ }; inline constexpr parallel_unsequenced_policy par_unseq{ /*unspecified*/ }; inline constexpr unsequenced_policy unseq{ /*unspecified*/ }; } ``` cpp Standard library header <format> (C++20) Standard library header <format> (C++20) ======================================== This header is part of the [format](../utility/format "cpp/utility/format") library. | | | --- | | Classes | | [formatter](../utility/format/formatter "cpp/utility/format/formatter") (C++20) | class template that defines formatting rules for a given type (class template) | | [basic\_format\_parse\_contextformat\_parse\_contextwformat\_parse\_context](../utility/format/basic_format_parse_context "cpp/utility/format/basic format parse context") (C++20)(C++20)(C++20) | formatting string parser state (class template) | | [basic\_format\_contextformat\_contextwformat\_context](../utility/format/basic_format_context "cpp/utility/format/basic format context") (C++20)(C++20)(C++20) | formatting state, including all formatting arguments and the output iterator (class template) | | [basic\_format\_arg](../utility/format/basic_format_arg "cpp/utility/format/basic format arg") (C++20) | class template that provides access to a formatting argument for user-defined formatters (class template) | | [basic\_format\_argsformat\_argswformat\_args](../utility/format/basic_format_args "cpp/utility/format/basic format args") (C++20)(C++20)(C++20) | class that provides access to all formatting arguments (class template) | | [basic\_format\_stringformat\_stringwformat\_string](../utility/format/basic_format_string "cpp/utility/format/basic format string") (C++20)(C++20)(C++20) | class template that performs compile-time format string checks at construction time (class template) | | [format\_error](../utility/format/format_error "cpp/utility/format/format error") (C++20) | exception type thrown on formatting errors (class) | | Functions | | [format](../utility/format/format "cpp/utility/format/format") (C++20) | stores formatted representation of the arguments in a new string (function template) | | [format\_to](../utility/format/format_to "cpp/utility/format/format to") (C++20) | writes out formatted representation of its arguments through an output iterator (function template) | | [format\_to\_n](../utility/format/format_to_n "cpp/utility/format/format to n") (C++20) | writes out formatted representation of its arguments through an output iterator, not exceeding specified size (function template) | | [formatted\_size](../utility/format/formatted_size "cpp/utility/format/formatted size") (C++20) | determines the number of characters necessary to store the formatted representation of its arguments (function template) | | [vformat](../utility/format/vformat "cpp/utility/format/vformat") (C++20) | non-template variant of `[std::format](../utility/format/format "cpp/utility/format/format")` using type-erased argument representation (function) | | [vformat\_to](../utility/format/vformat_to "cpp/utility/format/vformat to") (C++20) | non-template variant of `[std::format\_to](../utility/format/format_to "cpp/utility/format/format to")` using type-erased argument representation (function template) | | [visit\_format\_arg](../utility/format/visit_format_arg "cpp/utility/format/visit format arg") (C++20) | argument visitation interface for user-defined formatters (function template) | | [make\_format\_argsmake\_wformat\_args](../utility/format/make_format_args "cpp/utility/format/make format args") (C++20)(C++20) | creates a type-erased object referencing all formatting arguments, convertible to format\_args (function template) | ### Synopsis ``` namespace std { // class template basic_format_context template<class Out, class CharT> class basic_format_context; using format_context = basic_format_context</* unspecified */, char>; using wformat_context = basic_format_context</* unspecified */, wchar_t>; // class template basic_format_args template<class Context> class basic_format_args; using format_args = basic_format_args<format_context>; using wformat_args = basic_format_args<wformat_context>; // class template basic_format_string template<class CharT, class... Args> struct basic_format_string; template<class... Args> using format_string = basic_format_string<char, type_identity_t<Args>...>; template<class... Args> using wformat_string = basic_format_string<wchar_t, type_identity_t<Args>...>; // formatting functions template<class... Args> string format(format_string<Args...> fmt, Args&&... args); template<class... Args> wstring format(wformat_string<Args...> fmt, Args&&... args); template<class... Args> string format(const locale& loc, format_string<Args...> fmt, Args&&... args); template<class... Args> wstring format(const locale& loc, wformat_string<Args...> fmt, Args&&... args); string vformat(string_view fmt, format_args args); wstring vformat(wstring_view fmt, wformat_args args); string vformat(const locale& loc, string_view fmt, format_args args); wstring vformat(const locale& loc, wstring_view fmt, wformat_args args); template<class Out, class... Args> Out format_to(Out out, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> Out format_to(Out out, wformat_string<Args...> fmt, Args&&... args); template<class Out, class... Args> Out format_to(Out out, const locale& loc, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> Out format_to(Out out, const locale& loc, wformat_string<Args...> fmt, Args&&... args); template<class Out> Out vformat_to(Out out, string_view fmt, format_args args); template<class Out> Out vformat_to(Out out, wstring_view fmt, wformat_args args); template<class Out> Out vformat_to(Out out, const locale& loc, string_view fmt, format_args args); template<class Out> Out vformat_to(Out out, const locale& loc, wstring_view fmt, wformat_args args); template<class Out> struct format_to_n_result { Out out; iter_difference_t<Out> size; }; template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, wformat_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, const locale& loc, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, const locale& loc, wformat_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(format_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(wformat_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(const locale& loc, format_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(const locale& loc, wformat_string<Args...> fmt, Args&&... args); // formatter template<class T, class CharT = char> struct formatter; // concept formattable template<class T, class CharT> concept formattable = /* see description */; template<class R, class CharT> concept __const_formattable_range = // exposition only ranges::input_range<const R> && formattable<ranges::range_reference_t<const R>, CharT>; template<class R, class CharT> using __fmt_maybe_const = // exposition only conditional_t<__const_formattable_range<R, CharT>, const R, R>; // class template basic_format_parse_context template<class CharT> class basic_format_parse_context; using format_parse_context = basic_format_parse_context<char>; using wformat_parse_context = basic_format_parse_context<wchar_t>; // formatting of ranges // variable template format_kind enum class range_format { disabled, map, set, sequence, string, debug_string }; template<class R> constexpr /* unspecified */ format_kind = /* unspecified */; template<ranges::input_range R> requires same_as<R, remove_cvref_t<R>> constexpr range_format format_kind<R> = /* see description */; // class template range_formatter template<class T, class CharT = char> requires same_as<remove_cvref_t<T>, T> && formattable<T, CharT> class range_formatter; // class template range-default-formatter template<range_format K, ranges::input_range R, class CharT> struct __range_default_formatter; // exposition only // specializations for maps, sets, and strings template<ranges::input_range R, class CharT> requires (format_kind<R> != range_format::disabled) && formattable<ranges::range_reference_t<R>, CharT> struct formatter<R, CharT> : __range_default_formatter<format_kind<R>, R, CharT> { }; // arguments // class template basic_format_arg template<class Context> class basic_format_arg; template<class Visitor, class Context> decltype(auto) visit_format_arg(Visitor&& vis, basic_format_arg<Context> arg); // class template format-arg-store template<class Context, class... Args> class __format_arg_store; // exposition only template<class Context = format_context, class... Args> __format_arg_store<Context, Args...> make_format_args(Args&&... fmt_args); template<class... Args> __format_arg_store<wformat_context, Args...> make_wformat_args(Args&&... args); // class format_error class format_error; } ``` #### Class template `std::basic_format_string` ``` namespace std { template<class CharT, class... Args> struct basic_format_string { private: basic_string_view<CharT> str; // exposition only public: template<class T> consteval basic_format_string(const T& s); constexpr basic_string_view<CharT> get() const noexcept { return str; } }; } ``` #### Concept `std::formattable` ``` template<class T, class CharT> concept formattable = semiregular<formatter<remove_cvref_t<T>, CharT>> && requires(formatter<remove_cvref_t<T>, CharT> f, const formatter<remove_cvref_t<T>, CharT> cf, T t, basic_format_context<__fmt_iter_for<CharT>, CharT> fc, basic_format_parse_context<CharT> pc) { { f.parse(pc) } -> same_as<basic_format_parse_context<CharT>::iterator>; { cf.format(t, fc) } -> same_as<__fmt_iter_for<CharT>>; }; ``` #### Class template `[std::basic\_format\_parse\_context](../utility/format/basic_format_parse_context "cpp/utility/format/basic format parse context")` ``` namespace std { template<class CharT> class basic_format_parse_context { public: using char_type = CharT; using const_iterator = typename basic_string_view<CharT>::const_iterator; using iterator = const_iterator; private: iterator begin_; // exposition only iterator end_; // exposition only enum indexing { unknown, manual, automatic }; // exposition only indexing indexing_; // exposition only size_t next_arg_id_; // exposition only size_t num_args_; // exposition only public: constexpr explicit basic_format_parse_context(basic_string_view<CharT> fmt, size_t num_args = 0) noexcept; basic_format_parse_context(const basic_format_parse_context&) = delete; basic_format_parse_context& operator=(const basic_format_parse_context&) = delete; constexpr const_iterator begin() const noexcept; constexpr const_iterator end() const noexcept; constexpr void advance_to(const_iterator it); constexpr size_t next_arg_id(); constexpr void check_arg_id(size_t id); }; } ``` #### Class template `[std::basic\_format\_context](../utility/format/basic_format_context "cpp/utility/format/basic format context")` ``` namespace std { template<class Out, class CharT> class basic_format_context { basic_format_args<basic_format_context> args_; // exposition only Out out_; // exposition only public: using iterator = Out; using char_type = CharT; template<class T> using formatter_type = formatter<T, CharT>; basic_format_arg<basic_format_context> arg(size_t id) const noexcept; std::locale locale(); iterator out(); void advance_to(iterator it); }; } ``` #### Variable template `std::format_kind` ``` template<ranges::input_range R> requires same_as<R, remove_cvref_t<R>> constexpr range_format format_kind<R> = /* see description */; ``` #### Class template `std::range_formatter` ``` namespace std { template<class T, class CharT = char> requires same_as<remove_cvref_t<T>, T> && formattable<T, CharT> class range_formatter { formatter<T, CharT> underlying_; // exposition only basic_string_view<CharT> separator_ = // exposition only __STATICALLY_WIDEN<CharT>(", "); basic_string_view<CharT> __opening_bracket_ = // exposition only __STATICALLY_WIDEN<CharT>("["); basic_string_view<CharT> __closing_bracket_ = // exposition only __STATICALLY_WIDEN<CharT>("]"); public: constexpr void set_separator(basic_string_view<CharT> sep); constexpr void set_brackets(basic_string_view<CharT> opening, basic_string_view<CharT> closing); constexpr formatter<T, CharT>& underlying() { return underlying_; } constexpr const formatter<T, CharT>& underlying() const { return underlying_; } template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx); template<ranges::input_range R, class FormatContext> requires formattable<ranges::range_reference_t<R>, CharT> && same_as<remove_cvref_t<ranges::range_reference_t<R>>, T> typename FormatContext::iterator format(R&& r, FormatContext& ctx) const; }; } ``` #### Class template *`__range_default_formatter`* ``` namespace std { template<ranges::input_range R, class CharT> struct __range_default_formatter<range_format::sequence, R, CharT> { private: using __maybe_const_r = __fmt_maybe_const<R, CharT>; range_formatter<remove_cvref_t<ranges::range_reference_t<__maybe_const_r>>, CharT> underlying_; // exposition only public: constexpr void set_separator(basic_string_view<CharT> sep); constexpr void set_brackets(basic_string_view<CharT> opening, basic_string_view<CharT> closing); template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx); template<class FormatContext> typename FormatContext::iterator format(__maybe_const_r& elems, FormatContext& ctx) const; }; } ``` #### Specialization of *`__range_default_formatter`* for maps ``` namespace std { template<ranges::input_range R, class CharT> struct __range_default_formatter<range_format::map, R, CharT> { private: using __maybe_const_map = __fmt_maybe_const<R, CharT>; // exposition only using __element_type = // exposition only remove_cvref_t<ranges::range_reference_t<__maybe_const_map>>; range_formatter<__element_type, CharT> underlying_; // exposition only public: constexpr __range_default_formatter(); template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx); template<class FormatContext> typename FormatContext::iterator format(__maybe_const_map& r, FormatContext& ctx) const; }; } ``` #### Specialization of *`__range_default_formatter`* for sets ``` namespace std { template<ranges::input_range R, class CharT> struct __range_default_formatter<range_format::set, R, CharT> { private: using __maybe_const_set = __fmt_maybe_const<R, CharT>; // exposition only range_formatter<remove_cvref_t<ranges::range_reference_t<__maybe_const_set>>, CharT> underlying_; // exposition only public: constexpr __range_default_formatter(); template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx); template<class FormatContext> typename FormatContext::iterator format(__maybe_const_set& r, FormatContext& ctx) const; }; } ``` #### Specialization of *`__range_default_formatter`* for strings ``` namespace std { template<range_format K, ranges::input_range R, class CharT> requires (K == range_format::string || K == range_format::debug_string) struct __range_default_formatter<K, R, CharT> { private: formatter<basic_string<CharT>, CharT> underlying_; // exposition only public: template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx); template<class FormatContext> typename FormatContext::iterator format(/* see description */& str, FormatContext& ctx) const; }; } ``` #### Class template `[std::basic\_format\_arg](../utility/format/basic_format_arg "cpp/utility/format/basic format arg")` ``` namespace std { template<class Context> class basic_format_arg { public: class handle; private: using char_type = typename Context::char_type; // exposition only variant<monostate, bool, char_type, int, unsigned int, long long int, unsigned long long int, float, double, long double, const char_type*, basic_string_view<char_type>, const void*, handle> value; // exposition only template<class T> explicit basic_format_arg(T&& v) noexcept; // exposition only explicit basic_format_arg(float n) noexcept; // exposition only explicit basic_format_arg(double n) noexcept; // exposition only explicit basic_format_arg(long double n) noexcept; // exposition only explicit basic_format_arg(const char_type* s); // exposition only template<class traits> explicit basic_format_arg( basic_string_view<char_type, traits> s) noexcept; // exposition only template<class traits, class Allocator> explicit basic_format_arg( const basic_string<char_type, traits, Allocator>& s) noexcept; // exposition only explicit basic_format_arg(nullptr_t) noexcept; // exposition only template<class T> explicit basic_format_arg(T* p) noexcept; // exposition only public: basic_format_arg() noexcept; explicit operator bool() const noexcept; }; } ``` #### Class `std::basic_format_arg::handle` ``` namespace std { template<class Context> class basic_format_arg<Context>::handle { const void* ptr_; // exposition only void (*format_)(basic_format_parse_context<char_type>&, Context&, const void*); // exposition only template<class T> explicit handle(T&& val) noexcept; // exposition only friend class basic_format_arg<Context>; // exposition only public: void format(basic_format_parse_context<char_type>&, Context& ctx) const; }; } ``` #### Class template *`__format_arg_store`* ``` namespace std { template<class Context, class... Args> class __format_arg_store { // exposition only array<basic_format_arg<Context>, sizeof...(Args)> args; // exposition only }; } ``` #### Class template `[std::basic\_format\_args](../utility/format/basic_format_args "cpp/utility/format/basic format args")` ``` namespace std { template<class Context> class basic_format_args { size_t size_; // exposition only const basic_format_arg<Context>* data_; // exposition only public: basic_format_args() noexcept; template<class... Args> basic_format_args(const __format_arg_store<Context, Args...>& store) noexcept; basic_format_arg<Context> get(size_t i) const noexcept; }; } ``` #### Tuple formatter ``` namespace std { template<class CharT, formattable<CharT>... Ts> struct formatter<__pair_or_tuple<Ts...>, CharT> { private: tuple<formatter<remove_cvref_t<Ts>, CharT>...> underlying_; // exposition only basic_string_view<CharT> separator_ = // exposition only __STATICALLY_WIDEN<CharT>(", "); basic_string_view<CharT> opening_bracket_ = // exposition only __STATICALLY_WIDEN<CharT>("("); basic_string_view<CharT> closing_bracket_ = // exposition only __STATICALLY_WIDEN<CharT>(")"); public: constexpr void set_separator(basic_string_view<CharT> sep); constexpr void set_brackets(basic_string_view<CharT> opening, basic_string_view<CharT> closing); template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx); template<class FormatContext> typename FormatContext::iterator format(/* see description */& elems, FormatContext& ctx) const; }; } ``` #### Class `[std::format\_error](../utility/format/format_error "cpp/utility/format/format error")` ``` namespace std { class format_error : public runtime_error { public: explicit format_error(const string& what_arg); explicit format_error(const char* what_arg); }; } ```
programming_docs
cpp Standard library header <ostream> Standard library header <ostream> ================================= This header is part of the [Input/output](../io "cpp/io") library. | | | --- | | Classes | | [basic\_ostream](../io/basic_ostream "cpp/io/basic ostream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level output interface (class template) | | `[std::ostream](../io/basic_ostream "cpp/io/basic ostream")` | `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<char>` (typedef) | | `[std::wostream](../io/basic_ostream "cpp/io/basic ostream")` | `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<wchar\_t>` (typedef) | | Functions | | [operator<<(std::basic\_ostream)](../io/basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") | inserts character data or insert into rvalue stream (function template) | | [print](../io/basic_ostream/print "cpp/io/basic ostream/print") (C++23) | outputs [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [println](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/println&action=edit&redlink=1 "cpp/io/basic ostream/println (page does not exist)") (C++23) | outputs [formatted](../utility/format "cpp/utility/format") representation of the arguments with appended `'\n'` (function template) | | [vprint\_unicode](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/vprint_unicode&action=edit&redlink=1 "cpp/io/basic ostream/vprint unicode (page does not exist)") (C++23) | performs Unicode aware output using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [vprint\_nonunicode](https://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/vprint_nonunicode&action=edit&redlink=1 "cpp/io/basic ostream/vprint nonunicode (page does not exist)") (C++23) | outputs character data using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | Manipulators | | [endl](../io/manip/endl "cpp/io/manip/endl") | outputs `'\n'` and flushes the output stream (function template) | | [ends](../io/manip/ends "cpp/io/manip/ends") | outputs `'\0'` (function template) | | [flush](../io/manip/flush "cpp/io/manip/flush") | flushes the output stream (function template) | | [emit\_on\_flushnoemit\_on\_flush](../io/manip/emit_on_flush "cpp/io/manip/emit on flush") (C++20) | controls whether a stream's [`basic_syncbuf`](../io/basic_syncbuf "cpp/io/basic syncbuf") emits on flush (function template) | | [flush\_emit](../io/manip/flush_emit "cpp/io/manip/flush emit") (C++20) | flushes a stream and emits the content if it is using a [`basic_syncbuf`](../io/basic_syncbuf "cpp/io/basic syncbuf") (function template) | ### Synopsis ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ostream; using ostream = basic_ostream<char>; using wostream = basic_ostream<wchar_t>; template<class CharT, class Traits> basic_ostream<CharT, Traits>& endl(basic_ostream<CharT, Traits>& os); template<class CharT, class Traits> basic_ostream<CharT, Traits>& ends(basic_ostream<CharT, Traits>& os); template<class CharT, class Traits> basic_ostream<CharT, Traits>& flush(basic_ostream<CharT, Traits>& os); template<class CharT, class Traits> basic_ostream<CharT, Traits>& emit_on_flush(basic_ostream<CharT, Traits>& os); template<class CharT, class Traits> basic_ostream<CharT, Traits>& noemit_on_flush(basic_ostream<CharT, Traits>& os); template<class CharT, class Traits> basic_ostream<CharT, Traits>& flush_emit(basic_ostream<CharT, Traits>& os); template<class Ostream, class T> Ostream&& operator<<(Ostream&& os, const T& x); // print functions template<class... Args> void print(ostream& os, format_string<Args...> fmt, Args&&... args); template<class... Args> void println(ostream& os, format_string<Args...> fmt, Args&&... args); void vprint_unicode(ostream& os, string_view fmt, format_args args); void vprint_nonunicode(ostream& os, string_view fmt, format_args args); } ``` #### Class template `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ostream : virtual public basic_ios<CharT, Traits> { public: // types (inherited from basic_ios) using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructor/destructor explicit basic_ostream(basic_streambuf<char_type, Traits>* sb); virtual ~basic_ostream(); // prefix/suffix class sentry; // formatted output basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& (*pf)(basic_ostream<CharT, Traits>&)); basic_ostream<CharT, Traits>& operator<<(basic_ios<CharT, Traits>& (*pf)(basic_ios<CharT, Traits>&)); basic_ostream<CharT, Traits>& operator<<(ios_base& (*pf)(ios_base&)); basic_ostream<CharT, Traits>& operator<<(bool n); basic_ostream<CharT, Traits>& operator<<(short n); basic_ostream<CharT, Traits>& operator<<(unsigned short n); basic_ostream<CharT, Traits>& operator<<(int n); basic_ostream<CharT, Traits>& operator<<(unsigned int n); basic_ostream<CharT, Traits>& operator<<(long n); basic_ostream<CharT, Traits>& operator<<(unsigned long n); basic_ostream<CharT, Traits>& operator<<(long long n); basic_ostream<CharT, Traits>& operator<<(unsigned long long n); basic_ostream<CharT, Traits>& operator<<(float f); basic_ostream<CharT, Traits>& operator<<(double f); basic_ostream<CharT, Traits>& operator<<(long double f); basic_ostream<CharT, Traits>& operator<<(const void* p); basic_ostream<CharT, Traits>& operator<<(const volatile void* val); basic_ostream<CharT, Traits>& operator<<(nullptr_t); basic_ostream<CharT, Traits>& operator<<(basic_streambuf<char_type, Traits>* sb); // unformatted output basic_ostream<CharT, Traits>& put(char_type c); basic_ostream<CharT, Traits>& write(const char_type* s, streamsize n); basic_ostream<CharT, Traits>& flush(); // seeks pos_type tellp(); basic_ostream<CharT, Traits>& seekp(pos_type); basic_ostream<CharT, Traits>& seekp(off_type, ios_base::seekdir); protected: // copy/move constructor basic_ostream(const basic_ostream&) = delete; basic_ostream(basic_ostream&& rhs); // assign and swap basic_ostream& operator=(const basic_ostream&) = delete; basic_ostream& operator=(basic_ostream&& rhs); void swap(basic_ostream& rhs); }; // character inserters template<class CharT, class Traits> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>&, CharT); template<class CharT, class Traits> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>&, char); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, char); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, signed char); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, unsigned char); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, wchar_t) = delete; template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, char8_t) = delete; template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, char16_t) = delete; template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, char32_t) = delete; template<class Traits> basic_ostream<wchar_t, Traits>& operator<<(basic_ostream<wchar_t, Traits>&, char8_t) = delete; template<class Traits> basic_ostream<wchar_t, Traits>& operator<<(basic_ostream<wchar_t, Traits>&, char16_t) = delete; template<class Traits> basic_ostream<wchar_t, Traits>& operator<<(basic_ostream<wchar_t, Traits>&, char32_t) = delete; template<class CharT, class Traits> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>&, const CharT*); template<class CharT, class Traits> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>&, const char*); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const char*); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const signed char*); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const unsigned char*); template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const wchar_t*) = delete; template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const char8_t*) = delete; template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const char16_t*) = delete; template<class Traits> basic_ostream<char, Traits>& operator<<(basic_ostream<char, Traits>&, const char32_t*) = delete; template<class Traits> basic_ostream<wchar_t, Traits>& operator<<(basic_ostream<wchar_t, Traits>&, const char8_t*) = delete; template<class Traits> basic_ostream<wchar_t, Traits>& operator<<(basic_ostream<wchar_t, Traits>&, const char16_t*) = delete; template<class Traits> basic_ostream<wchar_t, Traits>& operator<<(basic_ostream<wchar_t, Traits>&, const char32_t*) = delete; } ``` #### Class `[std::basic\_ostream::sentry](../io/basic_ostream/sentry "cpp/io/basic ostream/sentry")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ostream<CharT, Traits>::sentry { bool ok_; // exposition only public: explicit sentry(basic_ostream<CharT, Traits>& os); ~sentry(); explicit operator bool() const { return ok_; } sentry(const sentry&) = delete; sentry& operator=(const sentry&) = delete; }; } ``` cpp Standard library header <bitset> Standard library header <bitset> ================================ This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Includes | | [<string>](string "cpp/header/string") | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` class template | | [<iosfwd>](iosfwd "cpp/header/iosfwd") | Forward declarations of all classes in the input/output library | | Classes | | [bitset](../utility/bitset "cpp/utility/bitset") | implements constant length bit array (class template) | | [std::hash<std::bitset>](../utility/bitset/hash "cpp/utility/bitset/hash") (C++11) | hash support for `[std::bitset](../utility/bitset "cpp/utility/bitset")` (class template specialization) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Functions | | [operator&operator|operator^](../utility/bitset/operator_logic2 "cpp/utility/bitset/operator logic2") | performs binary logic operations on bitsets (function template) | | [operator<<operator>>](../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") | performs stream input and output of bitsets (function template) | ### Synopsis ``` #include <string> #include <iosfwd> // for istream, ostream namespace std { template<size_t N> class bitset; // bitset operators template<size_t N> constexpr bitset<N> operator&(const bitset<N>&, const bitset<N>&) noexcept; template<size_t N> constexpr bitset<N> operator|(const bitset<N>&, const bitset<N>&) noexcept; template<size_t N> constexpr bitset<N> operator^(const bitset<N>&, const bitset<N>&) noexcept; template<class CharT, class Traits, size_t N> basic_istream<CharT, Traits>& operator>>(basic_istream<CharT, Traits>& is, bitset<N>& x); template<class CharT, class Traits, size_t N> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& os, const bitset<N>& x); } ``` #### Class template `[std::bitset](../utility/bitset "cpp/utility/bitset")` ``` namespace std { template<size_t N> class bitset { public: // bit reference class reference { friend class bitset; constexpr reference() noexcept; public: constexpr reference(const reference&) = default; constexpr ~reference(); constexpr reference& operator=(bool x) noexcept; // for b[i] = x; constexpr reference& operator=(const reference&) noexcept; // for b[i] = b[j]; constexpr bool operator~() const noexcept; // flips the bit constexpr operator bool() const noexcept; // for x = b[i]; constexpr reference& flip() noexcept; // for b[i].flip(); }; // constructors constexpr bitset() noexcept; constexpr bitset(unsigned long long val) noexcept; template<class CharT, class Traits, class Allocator> constexpr explicit bitset( const basic_string<CharT, Traits, Allocator>& str, typename basic_string<CharT, Traits, Allocator>::size_type pos = 0, typename basic_string<CharT, Traits, Allocator>::size_type n = basic_string<CharT, Traits, Allocator>::npos, CharT zero = CharT('0'), CharT one = CharT('1')); template<class CharT> constexpr explicit bitset( const CharT* str, typename basic_string<CharT>::size_type n = basic_string<CharT>::npos, CharT zero = CharT('0'), CharT one = CharT('1')); // bitset operations constexpr bitset& operator&=(const bitset& rhs) noexcept; constexpr bitset& operator|=(const bitset& rhs) noexcept; constexpr bitset& operator^=(const bitset& rhs) noexcept; constexpr bitset& operator<<=(size_t pos) noexcept; constexpr bitset& operator>>=(size_t pos) noexcept; constexpr bitset& set() noexcept; constexpr bitset& set(size_t pos, bool val = true); constexpr bitset& reset() noexcept; constexpr bitset& reset(size_t pos); constexpr bitset operator~() const noexcept; constexpr bitset& flip() noexcept; constexpr bitset& flip(size_t pos); // element access constexpr bool operator[](size_t pos) const; // for b[i]; constexpr reference operator[](size_t pos); // for b[i]; constexpr unsigned long to_ulong() const; constexpr unsigned long long to_ullong() const; template<class CharT = char, class Traits = char_Traits<CharT>, class Allocator = allocator<CharT>> constexpr basic_string<CharT, Traits, Allocator> to_string(CharT zero = CharT('0'), CharT one = CharT('1')) const; constexpr size_t count() const noexcept; constexpr size_t size() const noexcept; constexpr bool operator==(const bitset& rhs) const noexcept; constexpr bool test(size_t pos) const; constexpr bool all() const noexcept; constexpr bool any() const noexcept; constexpr bool none() const noexcept; constexpr bitset operator<<(size_t pos) const noexcept; constexpr bitset operator>>(size_t pos) const noexcept; }; // hash support template<class T> struct hash; template<size_t N> struct hash<bitset<N>>; } ``` cpp Standard library header <cfloat> Standard library header <cfloat> ================================ This header was originally in the C standard library as `<float.h>`. This header is part of the [type support](../types "cpp/types") library, in particular it's part of the [C numeric limits interface](../types/climits "cpp/types/climits"). ### Macros | | | | --- | --- | | FLT\_RADIX | the radix (integer base) used by the representation of all three floating-point types (macro constant) | | DECIMAL\_DIG (C++11) | conversion from `long double` to decimal with at least `DECIMAL_DIG` digits and back to `long double` is the identity conversion: this is the decimal precision required to serialize/deserialize a `long double` (see also `[std::numeric\_limits::max\_digits10](../types/numeric_limits/max_digits10 "cpp/types/numeric limits/max digits10")`) (macro constant) | | FLT\_DECIMAL\_DIGDBL\_DECIMAL\_DIGLDBL\_DECIMAL\_DIG (C++17) | conversion from `float`/`double`/`long double` to decimal with at least `FLT_DECIMAL_DIG`/`DBL_DECIMAL_DIG`/`LDBL_DECIMAL_DIG` digits and back is the identity conversion: this is the decimal precision required to serialize/deserialize a floating-point value (see also `[std::numeric\_limits::max\_digits10](../types/numeric_limits/max_digits10 "cpp/types/numeric limits/max digits10")`). Defined to at least `6`, `10`, and `10` respectively, or `9` for IEEE float and `17` for IEEE double. (macro constant) | | FLT\_MINDBL\_MINLDBL\_MIN | minimum normalized positive value of `float`, `double` and `long double` respectively (macro constant) | | FLT\_TRUE\_MINDBL\_TRUE\_MINLDBL\_TRUE\_MIN (C++17) | minimum positive value of `float`, `double` and `long double` respectively (macro constant) | | FLT\_MAXDBL\_MAXLDBL\_MAX | maximum finite value of `float`, `double` and `long double` respectively (macro constant) | | FLT\_EPSILONDBL\_EPSILONLDBL\_EPSILON | difference between `1.0` and the next representable value for `float`, `double` and `long double` respectively (macro constant) | | FLT\_DIGDBL\_DIGLDBL\_DIG | number of decimal digits that are guaranteed to be preserved in text → `float`/`double`/`long double` → text roundtrip without change due to rounding or overflow (see `[std::numeric\_limits::digits10](../types/numeric_limits/digits10 "cpp/types/numeric limits/digits10")` for explanation) (macro constant) | | FLT\_MANT\_DIGDBL\_MANT\_DIGLDBL\_MANT\_DIG | number of base `FLT_RADIX` digits that can be represented without losing precision for `float`, `double` and `long double` respectively (macro constant) | | FLT\_MIN\_EXPDBL\_MIN\_EXPLDBL\_MIN\_EXP | minimum negative integer such that `FLT_RADIX` raised by power one less than that integer is a normalized `float`, `double` and `long double` respectively (macro constant) | | FLT\_MIN\_10\_EXPDBL\_MIN\_10\_EXPLDBL\_MIN\_10\_EXP | minimum negative integer such that 10 raised to that power is a normalized `float`, `double` and `long double` respectively (macro constant) | | FLT\_MAX\_EXPDBL\_MAX\_EXPLDBL\_MAX\_EXP | maximum positive integer such that `FLT_RADIX` raised by power one less than that integer is a representable finite `float`, `double` and `long double` respectively (macro constant) | | FLT\_MAX\_10\_EXPDBL\_MAX\_10\_EXPLDBL\_MAX\_10\_EXP | maximum positive integer such that 10 raised to that power is a representable finite `float`, `double` and `long double` respectively (macro constant) | | [FLT\_ROUNDS](../types/climits/flt_rounds "cpp/types/climits/FLT ROUNDS") | default rounding mode of floating-point arithmetics (macro constant) | | [FLT\_EVAL\_METHOD](../types/climits/flt_eval_method "cpp/types/climits/FLT EVAL METHOD") (C++11) | specifies in what precision all arithmetic operations are done (macro constant) | | FLT\_HAS\_SUBNORMDBL\_HAS\_SUBNORMLDBL\_HAS\_SUBNORM (C++17) | specifies whether the type supports subnormal ([denormal](https://en.wikipedia.org/wiki/Denormal_number "enwiki:Denormal number")) numbers: `-1` – indeterminable, `​0​` – absent, `1` – present (macro constant) | ### Synopsis ``` #define FLT_ROUNDS /* see definition */ #define FLT_EVAL_METHOD /* see definition */ #define FLT_HAS_SUBNORM /* see definition */ #define DBL_HAS_SUBNORM /* see definition */ #define LDBL_HAS_SUBNORM /* see definition */ #define FLT_RADIX /* see definition */ #define FLT_MANT_DIG /* see definition */ #define DBL_MANT_DIG /* see definition */ #define LDBL_MANT_DIG /* see definition */ #define FLT_DECIMAL_DIG /* see definition */ #define DBL_DECIMAL_DIG /* see definition */ #define LDBL_DECIMAL_DIG /* see definition */ #define DECIMAL_DIG /* see definition */ #define FLT_DIG /* see definition */ #define DBL_DIG /* see definition */ #define LDBL_DIG /* see definition */ #define FLT_MIN_EXP /* see definition */ #define DBL_MIN_EXP /* see definition */ #define LDBL_MIN_EXP /* see definition */ #define FLT_MIN_10_EXP /* see definition */ #define DBL_MIN_10_EXP /* see definition */ #define LDBL_MIN_10_EXP /* see definition */ #define FLT_MAX_EXP /* see definition */ #define DBL_MAX_EXP /* see definition */ #define LDBL_MAX_EXP /* see definition */ #define FLT_MAX_10_EXP /* see definition */ #define DBL_MAX_10_EXP /* see definition */ #define LDBL_MAX_10_EXP /* see definition */ #define FLT_MAX /* see definition */ #define DBL_MAX /* see definition */ #define LDBL_MAX /* see definition */ #define FLT_EPSILON /* see definition */ #define DBL_EPSILON /* see definition */ #define LDBL_EPSILON /* see definition */ #define FLT_MIN /* see definition */ #define DBL_MIN /* see definition */ #define LDBL_MIN /* see definition */ #define FLT_TRUE_MIN /* see definition */ #define DBL_TRUE_MIN /* see definition */ #define LDBL_TRUE_MIN /* see definition */ ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/types/limits#Limits_of_floating-point_types "c/types/limits") for Limits of floating-point types |
programming_docs
cpp Standard library header <flat_set> (C++23) Standard library header <flat\_set> (C++23) =========================================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [flat\_set](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_set&action=edit&redlink=1 "cpp/container/flat set (page does not exist)") (C++23) | adapts a container to provide a collection of unique keys, sorted by keys (class template) | | [flat\_multiset](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multiset&action=edit&redlink=1 "cpp/container/flat multiset (page does not exist)") (C++23) | adapts a container to provide a collection of keys, sorted by keys (class template) | | [sorted\_unique\_t](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_unique&action=edit&redlink=1 "cpp/container/sorted unique (page does not exist)") (C++23) | a tag type used to indicate that elements of a container or range are sorted and unique (class) | | [sorted\_equivalent\_t](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_equivalent&action=edit&redlink=1 "cpp/container/sorted equivalent (page does not exist)") (C++23) | a tag type used to indicate that elements of a container or range are sorted (uniqueness is not required) (class) | | [std::uses\_allocator<std::flat\_set>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_set/uses_allocator&action=edit&redlink=1 "cpp/container/flat set/uses allocator (page does not exist)") (C++23) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | [std::uses\_allocator<std::flat\_multiset>](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multiset/uses_allocator&action=edit&redlink=1 "cpp/container/flat multiset/uses allocator (page does not exist)") (C++23) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | Functions | | [erase\_if(std::flat\_set)](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_set/erase_if&action=edit&redlink=1 "cpp/container/flat set/erase if (page does not exist)") (C++23) | Erases all elements satisfying specific criteria (function template) | | [erase\_if(std::flat\_multiset)](https://en.cppreference.com/mwiki/index.php?title=cpp/container/flat_multiset/erase_if&action=edit&redlink=1 "cpp/container/flat multiset/erase if (page does not exist)") (C++23) | Erases all elements satisfying specific criteria (function template) | | Constants | | [sorted\_unique](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_unique&action=edit&redlink=1 "cpp/container/sorted unique (page does not exist)") (C++23) | an object of type `std::sorted_unique_t` (constant) | | [sorted\_equivalent](https://en.cppreference.com/mwiki/index.php?title=cpp/container/sorted_equivalent&action=edit&redlink=1 "cpp/container/sorted equivalent (page does not exist)") (C++23) | an object of type `std::sorted_equivalent_t` (constant) | ### Synopsis ``` #include <initializer_list> namespace std { // class template flat_set template<class Key, class Compare = less<Key>, class KeyContainer = vector<Key>> class flat_set; struct sorted_unique_t { explicit sorted_unique_t() = default; }; inline constexpr sorted_unique_t sorted_unique{}; template<class Key, class Compare, class KeyContainer, class Predicate> size_t erase_if(flat_set<Key, Compare, KeyContainer>& c, Predicate pred); template<class Key, class Compare, class KeyContainer, class Allocator> struct uses_allocator<flat_set<Key, Compare, KeyContainer>, Allocator>; // class template flat_multiset template<class Key, class Compare = less<Key>, class KeyContainer = vector<Key>> class flat_multiset; struct sorted_equivalent_t { explicit sorted_equivalent_t() = default; }; inline constexpr sorted_equivalent_t sorted_equivalent{}; template<class Key, class Compare, class KeyContainer, class Predicate> size_t erase_if(flat_multiset<Key, Compare, KeyContainer>& c, Predicate pred); template<class Key, class Compare, class KeyContainer, class Allocator> struct uses_allocator<flat_multiset<Key, Compare, KeyContainer>, Allocator>; } ``` #### Class template `std::flat_set` ``` namespace std { template<class Key, class Compare = less<Key>, class KeyContainer = vector<Key>> class flat_set { public: // types using key_type = Key; using value_type = Key; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using size_type = typename KeyContainer::size_type; using difference_type = typename KeyContainer::difference_type; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using container_type = KeyContainer; // constructors flat_set() : flat_set(key_compare()) { } explicit flat_set(container_type cont); template<class Allocator> flat_set(const container_type& cont, const Allocator& a); flat_set(sorted_unique_t, container_type cont) : c(std::move(cont)), compare(key_compare()) { } template<class Allocator> flat_set(sorted_unique_t, const container_type& cont, const Allocator& a); explicit flat_set(const key_compare& comp) : c(), compare(comp) { } template<class Allocator> flat_set(const key_compare& comp, const Allocator& a); template<class Allocator> explicit flat_set(const Allocator& a); template<class InputIterator> flat_set(InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(), compare(comp) { insert(first, last); } template<class InputIterator, class Allocator> flat_set(InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_set(InputIterator first, InputIterator last, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_set(from_range_t fr, R&& rg) : flat_set(fr, std::forward<R>(range), key_compare()) { } template</*container-compatible-range*/<value_type> R, class Allocator> flat_set(from_range_t, R&& rg, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_set(from_range_t, R&& rg, const key_compare& comp) : flat_set(comp) { insert_range(std::forward<R>(range)); } template</*container-compatible-range*/<value_type> R, class Allocator> flat_set(from_range_t, R&& rg, const key_compare& comp, const Allocator& a); template<class InputIterator> flat_set(sorted_unique_t, InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(first, last), compare(comp) { } template<class InputIterator, class Allocator> flat_set(sorted_unique_t, InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_set(sorted_unique_t, InputIterator first, InputIterator last, const Allocator& a); flat_set(initializer_list<key_type> il, const key_compare& comp = key_compare()) : flat_set(il.begin(), il.end(), comp) { } template<class Allocator> flat_set(initializer_list<key_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_set(initializer_list<key_type> il, const Allocator& a); flat_set(sorted_unique_t s, initializer_list<key_type> il, const key_compare& comp = key_compare()) : flat_set(s, il.begin(), il.end(), comp) { } template<class Allocator> flat_set(sorted_unique_t, initializer_list<key_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_set(sorted_unique_t, initializer_list<key_type> il, const Allocator& a); flat_set& operator=(initializer_list<key_type>); // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> pair<iterator, bool> emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); pair<iterator, bool> insert(const value_type& x) { return emplace(x); } pair<iterator, bool> insert(value_type&& x) { return emplace(std::move(x)); } template<class K> pair<iterator, bool> insert(K&& x); iterator insert(const_iterator position, const value_type& x) { return emplace_hint(position, x); } iterator insert(const_iterator position, value_type&& x) { return emplace_hint(position, std::move(x)); } template<class K> iterator insert(const_iterator hint, K&& x); template<class InputIterator> void insert(InputIterator first, InputIterator last); template<class InputIterator> void insert(sorted_unique_t, InputIterator first, InputIterator last); template</*container-compatible-range*/<value_type> R> void insert_range(R&& rg); void insert(initializer_list<key_type> il) { insert(il.begin(), il.end()); } void insert(sorted_unique_t s, initializer_list<key_type> il) { insert(s, il.begin(), il.end()); } container_type extract() &&; void replace(container_type&&); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(flat_set& y) noexcept; void clear() noexcept; // observers key_compare key_comp() const; value_compare value_comp() const; // set operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; friend bool operator==(const flat_set& x, const flat_set& y); friend /*synth-three-way-result*/<value_type> operator<=>(const flat_set& x, const flat_set& y); friend void swap(flat_set& x, flat_set& y) noexcept { x.swap(y); } private: container_type c; // exposition only key_compare compare; // exposition only }; template<class InputIterator, class Compare = less</*iter-value-type*/<InputIterator>>> flat_set(InputIterator, InputIterator, Compare = Compare()) -> flat_set</*iter-value-type*/<InputIterator>, Compare>; template<class InputIterator, class Compare = less</*iter-value-type*/<InputIterator>>> flat_set(sorted_unique_t, InputIterator, InputIterator, Compare = Compare()) -> flat_set</*iter-value-type*/<InputIterator>, Compare>; template<ranges::input_range R, class Compare = less<ranges::range_value_t<R>>, class Allocator = allocator<ranges::range_value_t<R>>> flat_set(from_range_t, R&&, Compare = Compare(), Allocator = Allocator()) -> flat_set<ranges::range_value_t<R>, Compare>; template<ranges::input_range R, class Allocator> flat_set(from_range_t, R&&, Allocator) -> flat_set<ranges::range_value_t<R>, less<ranges::range_value_t<R>>>; template<class Key, class Compare = less<Key>> flat_set(initializer_list<Key>, Compare = Compare()) -> flat_set<Key, Compare>; template<class Key, class Compare = less<Key>> flat_set(sorted_unique_t, initializer_list<Key>, Compare = Compare()) -> flat_set<Key, Compare>; template<class Key, class Compare, class KeyContainer, class Allocator> struct uses_allocator<flat_set<Key, Compare, KeyContainer>, Allocator> : bool_constant<uses_allocator_v<KeyContainer, Allocator>> { }; } ``` #### Class template `std::flat_multiset` ``` namespace std { template<class Key, class Compare = less<Key>, class KeyContainer = vector<Key>> class flat_multiset { public: // types using key_type = Key; using value_type = Key; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using size_type = typename KeyContainer::size_type; using difference_type = typename KeyContainer::difference_type; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using container_type = KeyContainer; // constructors flat_multiset() : flat_multiset(key_compare()) { } explicit flat_multiset(container_type cont); template<class Allocator> flat_multiset(const container_type& cont, const Allocator& a); flat_multiset(sorted_equivalent_t, container_type cont) : c(std::move(cont)), compare(key_compare()) { } template<class Allocator> flat_multiset(sorted_equivalent_t, const container_type&, const Allocator& a); explicit flat_multiset(const key_compare& comp) : c(), compare(comp) { } template<class Allocator> flat_multiset(const key_compare& comp, const Allocator& a); template<class Allocator> explicit flat_multiset(const Allocator& a); template<class InputIterator> flat_multiset(InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(), compare(comp) { insert(first, last); } template<class InputIterator, class Allocator> flat_multiset(InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_multiset(InputIterator first, InputIterator last, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_multiset(from_range_t fr, R&& rg) : flat_multiset(fr, std::forward<R>(range), key_compare()) { } template</*container-compatible-range*/<value_type> R, class Allocator> flat_multiset(from_range_t, R&& rg, const Allocator& a); template</*container-compatible-range*/<value_type> R> flat_multiset(from_range_t, R&& rg, const key_compare& comp) : flat_multiset(comp) { insert_range(std::forward<R>(range)); } template</*container-compatible-range*/<value_type> R, class Allocator> flat_multiset(from_range_t, R&& rg, const key_compare& comp, const Allocator& a); template<class InputIterator> flat_multiset(sorted_equivalent_t, InputIterator first, InputIterator last, const key_compare& comp = key_compare()) : c(first, last), compare(comp) { } template<class InputIterator, class Allocator> flat_multiset(sorted_equivalent_t, InputIterator first, InputIterator last, const key_compare& comp, const Allocator& a); template<class InputIterator, class Allocator> flat_multiset(sorted_equivalent_t, InputIterator first, InputIterator last, const Allocator& a); flat_multiset(initializer_list<key_type> il, const key_compare& comp = key_compare()) : flat_multiset(il.begin(), il.end(), comp) { } template<class Allocator> flat_multiset(initializer_list<key_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_multiset(initializer_list<key_type> il, const Allocator& a); flat_multiset(sorted_equivalent_t s, initializer_list<key_type> il, const key_compare& comp = key_compare()) : flat_multiset(s, il.begin(), il.end(), comp) { } template<class Allocator> flat_multiset(sorted_equivalent_t, initializer_list<key_type> il, const key_compare& comp, const Allocator& a); template<class Allocator> flat_multiset(sorted_equivalent_t, initializer_list<key_type> il, const Allocator& a); flat_multiset& operator=(initializer_list<key_type>); // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> iterator emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& x) { return emplace(x); } iterator insert(value_type&& x) { return emplace(std::move(x)); } iterator insert(const_iterator position, const value_type& x) { return emplace_hint(position, x); } iterator insert(const_iterator position, value_type&& x) { return emplace_hint(position, std::move(x)); } template<class InputIterator> void insert(InputIterator first, InputIterator last); template<class InputIterator> void insert(sorted_equivalent_t, InputIterator first, InputIterator last); template</*container-compatible-range*/<value_type> R> void insert_range(R&& rg); void insert(initializer_list<key_type> il) { insert(il.begin(), il.end()); } void insert(sorted_equivalent_t s, initializer_list<key_type> il) { insert(s, il.begin(), il.end()); } container_type extract() &&; void replace(container_type&&); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& x); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(flat_multiset& y) noexcept; void clear() noexcept; // observers key_compare key_comp() const; value_compare value_comp() const; // set operations iterator find(const key_type& x); const_iterator find(const key_type& x) const; template<class K> iterator find(const K& x); template<class K> const_iterator find(const K& x) const; size_type count(const key_type& x) const; template<class K> size_type count(const K& x) const; bool contains(const key_type& x) const; template<class K> bool contains(const K& x) const; iterator lower_bound(const key_type& x); const_iterator lower_bound(const key_type& x) const; template<class K> iterator lower_bound(const K& x); template<class K> const_iterator lower_bound(const K& x) const; iterator upper_bound(const key_type& x); const_iterator upper_bound(const key_type& x) const; template<class K> iterator upper_bound(const K& x); template<class K> const_iterator upper_bound(const K& x) const; pair<iterator, iterator> equal_range(const key_type& x); pair<const_iterator, const_iterator> equal_range(const key_type& x) const; template<class K> pair<iterator, iterator> equal_range(const K& x); template<class K> pair<const_iterator, const_iterator> equal_range(const K& x) const; friend bool operator==(const flat_multiset& x, const flat_multiset& y); friend /*synth-three-way-result*/<value_type> operator<=>(const flat_multiset& x, const flat_multiset& y); friend void swap(flat_multiset& x, flat_multiset& y) noexcept { x.swap(y); } private: container_type c; // exposition only key_compare compare; // exposition only }; template<class InputIterator, class Compare = less</*iter-value-type*/<InputIterator>>> flat_multiset(InputIterator, InputIterator, Compare = Compare()) -> flat_multiset</*iter-value-type*/<InputIterator>, /*iter-value-type*/<InputIterator>, Compare>; template<class InputIterator, class Compare = less</*iter-value-type*/<InputIterator>>> flat_multiset(sorted_equivalent_t, InputIterator, InputIterator, Compare = Compare()) -> flat_multiset</*iter-value-type*/<InputIterator>, /*iter-value-type*/<InputIterator>, Compare>; template<ranges::input_range R, class Compare = less<ranges::range_value_t<R>>, class Allocator = allocator<ranges::range_value_t<R>>> flat_multiset(from_range_t, R&&, Compare = Compare(), Allocator = Allocator()) -> flat_multiset<ranges::range_value_t<R>, Compare>; template<ranges::input_range R, class Allocator> flat_multiset(from_range_t, R&&, Allocator) -> flat_multiset<ranges::range_value_t<R>, less<ranges::range_value_t<R>>>; template<class Key, class Compare = less<Key>> flat_multiset(initializer_list<Key>, Compare = Compare()) -> flat_multiset<Key, Compare>; template<class Key, class Compare = less<Key>> flat_multiset(sorted_equivalent_t, initializer_list<Key>, Compare = Compare()) -> flat_multiset<Key, Compare>; template<class Key, class Compare, class KeyContainer, class Allocator> struct uses_allocator<flat_multiset<Key, Compare, KeyContainer>, Allocator> : bool_constant<uses_allocator_v<KeyContainer, Allocator>> { }; } ``` ### References * C++23 standard (ISO/IEC 14882:2023): + 24.6.5 Header `<flat_set>` synopsis [flat.set.syn] + 24.6.11.2 Definition [flat.set.defn] + 24.6.12.2 Definition [flat.multiset.defn]
programming_docs
cpp Standard library header <mutex> (C++11) Standard library header <mutex> (C++11) ======================================= This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [mutex](../thread/mutex "cpp/thread/mutex") (C++11) | provides basic mutual exclusion facility (class) | | [timed\_mutex](../thread/timed_mutex "cpp/thread/timed mutex") (C++11) | provides mutual exclusion facility which implements locking with a timeout (class) | | [recursive\_mutex](../thread/recursive_mutex "cpp/thread/recursive mutex") (C++11) | provides mutual exclusion facility which can be locked recursively by the same thread (class) | | [recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex") (C++11) | provides mutual exclusion facility which can be locked recursively by the same thread and implements locking with a timeout (class) | | [lock\_guard](../thread/lock_guard "cpp/thread/lock guard") (C++11) | implements a strictly scope-based mutex ownership wrapper (class template) | | [unique\_lock](../thread/unique_lock "cpp/thread/unique lock") (C++11) | implements movable mutex ownership wrapper (class template) | | [scoped\_lock](../thread/scoped_lock "cpp/thread/scoped lock") (C++17) | deadlock-avoiding RAII wrapper for multiple mutexes (class template) | | [defer\_lock\_ttry\_to\_lock\_tadopt\_lock\_t](../thread/lock_tag_t "cpp/thread/lock tag t") (C++11)(C++11)(C++11) | tag type used to specify locking strategy (class) | | [once\_flag](../thread/once_flag "cpp/thread/once flag") (C++11) | helper object to ensure that [`call_once`](../thread/call_once "cpp/thread/call once") invokes the function only once (class) | | Constants | | [defer\_locktry\_to\_lockadopt\_lock](../thread/lock_tag "cpp/thread/lock tag") (C++11)(C++11)(C++11) | tag constants used to specify locking strategy (constant) | | Functions | | [try\_lock](../thread/try_lock "cpp/thread/try lock") (C++11) | attempts to obtain ownership of mutexes via repeated calls to `try_lock` (function template) | | [lock](../thread/lock "cpp/thread/lock") (C++11) | locks specified mutexes, blocks if any are unavailable (function template) | | [call\_once](../thread/call_once "cpp/thread/call once") (C++11) | invokes a function only once even if called from multiple threads (function template) | | [std::swap(std::unique\_lock)](../thread/unique_lock/swap2 "cpp/thread/unique lock/swap2") (C++11) | specialization of `[std::swap](../algorithm/swap "cpp/algorithm/swap")` for `unique_lock` (function template) | ### Synopsis ``` namespace std { class mutex; class recursive_mutex; class timed_mutex; class recursive_timed_mutex; struct defer_lock_t { explicit defer_lock_t() = default; }; struct try_to_lock_t { explicit try_to_lock_t() = default; }; struct adopt_lock_t { explicit adopt_lock_t() = default; }; inline constexpr defer_lock_t defer_lock { }; inline constexpr try_to_lock_t try_to_lock { }; inline constexpr adopt_lock_t adopt_lock { }; template<class Mutex> class lock_guard; template<class... MutexTypes> class scoped_lock; template<class Mutex> class unique_lock; template<class Mutex> void swap(unique_lock<Mutex>& x, unique_lock<Mutex>& y) noexcept; template<class L1, class L2, class... L3> int try_lock(L1&, L2&, L3&...); template<class L1, class L2, class... L3> void lock(L1&, L2&, L3&...); struct once_flag; template<class Callable, class... Args> void call_once(once_flag& flag, Callable&& func, Args&&... args); } ``` #### Class `[std::mutex](../thread/mutex "cpp/thread/mutex")` ``` namespace std { class mutex { public: constexpr mutex() noexcept; ~mutex(); mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; void lock(); bool try_lock(); void unlock(); using native_handle_type = /* implementation-defined */; native_handle_type native_handle(); }; } ``` #### Class `[std::recursive\_mutex](../thread/recursive_mutex "cpp/thread/recursive mutex")` ``` namespace std { class recursive_mutex { public: recursive_mutex(); ~recursive_mutex(); recursive_mutex(const recursive_mutex&) = delete; recursive_mutex& operator=(const recursive_mutex&) = delete; void lock(); bool try_lock() noexcept; void unlock(); using native_handle_type = /* implementation-defined */; native_handle_type native_handle(); }; } ``` #### Class `[std::timed\_mutex](../thread/timed_mutex "cpp/thread/timed mutex")` ``` namespace std { class timed_mutex { public: timed_mutex(); ~timed_mutex(); timed_mutex(const timed_mutex&) = delete; timed_mutex& operator=(const timed_mutex&) = delete; void lock(); // blocking bool try_lock(); template<class Rep, class Period> bool try_lock_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time); void unlock(); using native_handle_type = /* implementation-defined */; native_handle_type native_handle(); }; } ``` #### Class `[std::recursive\_timed\_mutex](../thread/recursive_timed_mutex "cpp/thread/recursive timed mutex")` ``` namespace std { class recursive_timed_mutex { public: recursive_timed_mutex(); ~recursive_timed_mutex(); recursive_timed_mutex(const recursive_timed_mutex&) = delete; recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete; void lock(); // blocking bool try_lock() noexcept; template<class Rep, class Period> bool try_lock_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time); void unlock(); using native_handle_type = /* implementation-defined */; native_handle_type native_handle(); }; } ``` #### Class template `[std::lock\_guard](../thread/lock_guard "cpp/thread/lock guard")` ``` namespace std { template<class Mutex> class lock_guard { public: using mutex_type = Mutex; explicit lock_guard(mutex_type& m); lock_guard(mutex_type& m, adopt_lock_t); ~lock_guard(); lock_guard(const lock_guard&) = delete; lock_guard& operator=(const lock_guard&) = delete; private: mutex_type& pm; // exposition only }; } ``` #### Class template `std::scoped_lock` ``` namespace std { template<class... MutexTypes> class scoped_lock { public: using mutex_type = Mutex; // If MutexTypes... consists of the single type Mutex explicit scoped_lock(MutexTypes&... m); explicit scoped_lock(adopt_lock_t, MutexTypes&... m); ~scoped_lock(); scoped_lock(const scoped_lock&) = delete; scoped_lock& operator=(const scoped_lock&) = delete; private: tuple<MutexTypes&...> pm; // exposition only }; } ``` #### Class template `[std::unique\_lock](../thread/unique_lock "cpp/thread/unique lock")` ``` namespace std { template<class Mutex> class unique_lock { public: using mutex_type = Mutex; // construct/copy/destroy unique_lock() noexcept; explicit unique_lock(mutex_type& m); unique_lock(mutex_type& m, defer_lock_t) noexcept; unique_lock(mutex_type& m, try_to_lock_t); unique_lock(mutex_type& m, adopt_lock_t); template<class Clock, class Duration> unique_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time); template<class Rep, class Period> unique_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time); ~unique_lock(); unique_lock(const unique_lock&) = delete; unique_lock& operator=(const unique_lock&) = delete; unique_lock(unique_lock&& u) noexcept; unique_lock& operator=(unique_lock&& u); // locking void lock(); bool try_lock(); template<class Rep, class Period> bool try_lock_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time); void unlock(); // modifiers void swap(unique_lock& u) noexcept; mutex_type* release() noexcept; // observers bool owns_lock() const noexcept; explicit operator bool () const noexcept; mutex_type* mutex() const noexcept; private: mutex_type* pm; // exposition only bool owns; // exposition only }; template<class Mutex> void swap(unique_lock<Mutex>& x, unique_lock<Mutex>& y) noexcept; } ``` #### Class `[std::once\_flag](../thread/once_flag "cpp/thread/once flag")` ``` namespace std { struct once_flag { constexpr once_flag() noexcept; once_flag(const once_flag&) = delete; once_flag& operator=(const once_flag&) = delete; }; } ``` cpp Standard library header <syncstream> (C++20) Standard library header <syncstream> (C++20) ============================================ This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Includes | | [<ostream>](ostream "cpp/header/ostream") | `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")`, `[std::basic\_iostream](../io/basic_iostream "cpp/io/basic iostream")` class templates and several typedefs | | Classes | | [basic\_syncbuf](../io/basic_syncbuf "cpp/io/basic syncbuf") (C++20) | synchronized output device wrapper (class template) | | [basic\_osyncstream](../io/basic_osyncstream "cpp/io/basic osyncstream") (C++20) | synchronized output stream wrapper (class template) | | `syncbuf` (C++20) | `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)<char>`(typedef) | | `wsyncbuf` (C++20) | `[std::basic\_syncbuf](http://en.cppreference.com/w/cpp/io/basic_syncbuf)<wchar\_t>`(typedef) | | `osyncstream` (C++20) | `[std::basic\_osyncstream](http://en.cppreference.com/w/cpp/io/basic_osyncstream)<char>`(typedef) | | `wosyncstream` (C++20) | `[std::basic\_osyncstream](http://en.cppreference.com/w/cpp/io/basic_osyncstream)<wchar\_t>`(typedef) | | Functions | | [std::swap(std::basic\_syncbuf)](../io/basic_syncbuf/swap2 "cpp/io/basic syncbuf/swap2") (C++20) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` #include <ostream> namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_syncbuf; using syncbuf = basic_syncbuf<char>; using wsyncbuf = basic_syncbuf<wchar_t>; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_osyncstream; using osyncstream = basic_osyncstream<char>; using wosyncstream = basic_osyncstream<wchar_t>; } ``` #### Class template `std::basic_syncbuf` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_syncbuf : public basic_streambuf<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; using allocator_type = Allocator; using streambuf_type = basic_streambuf<CharT, Traits>; // construction and destruction basic_syncbuf() : basic_syncbuf(nullptr) {} explicit basic_syncbuf(streambuf_type* obuf) : basic_syncbuf(obuf, Allocator()) {} basic_syncbuf(streambuf_type*, const Allocator&); basic_syncbuf(basic_syncbuf&&); ~basic_syncbuf(); // assignment and swap basic_syncbuf& operator=(basic_syncbuf&&); void swap(basic_syncbuf&); // member functions bool emit(); streambuf_type* get_wrapped() const noexcept; allocator_type get_allocator() const noexcept; void set_emit_on_sync(bool) noexcept; protected: // overridden virtual functions int sync() override; private: streambuf_type* wrapped; // exposition only bool emit_on_sync{}; // exposition only }; // specialized algorithms template<class CharT, class Traits, class Allocator> void swap(basic_syncbuf<CharT, Traits, Allocator>&, basic_syncbuf<CharT, Traits, Allocator>&); } ``` #### Class template `std::basic_osyncstream` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_osyncstream : public basic_ostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; using allocator_type = Allocator; using streambuf_type = basic_streambuf<CharT, Traits>; using syncbuf_type = basic_syncbuf<CharT, Traits, Allocator>; // construction and destruction basic_osyncstream(streambuf_type*, const Allocator&); explicit basic_osyncstream(streambuf_type* obuf) : basic_osyncstream(obuf, Allocator()) {} basic_osyncstream(basic_ostream<CharT, Traits>& os, const Allocator& allocator) : basic_osyncstream(os.rdbuf(), allocator) {} explicit basic_osyncstream(basic_ostream<CharT, Traits>& os) : basic_osyncstream(os, Allocator()) {} basic_osyncstream(basic_osyncstream&&) noexcept; ~basic_osyncstream(); // assignment basic_osyncstream& operator=(basic_osyncstream&&) noexcept; // member functions void emit(); streambuf_type* get_wrapped() const noexcept; syncbuf_type* rdbuf() const noexcept { return const_cast<syncbuf_type*>(addressof(sb)); } private: syncbuf_type sb; // exposition only }; } ``` cpp Standard library header <shared_mutex> (C++14) Standard library header <shared\_mutex> (C++14) =============================================== This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [shared\_mutex](../thread/shared_mutex "cpp/thread/shared mutex") (C++17) | provides shared mutual exclusion facility (class) | | [shared\_timed\_mutex](../thread/shared_timed_mutex "cpp/thread/shared timed mutex") (C++14) | provides shared mutual exclusion facility and implements locking with a timeout (class) | | [shared\_lock](../thread/shared_lock "cpp/thread/shared lock") (C++14) | implements movable shared mutex ownership wrapper (class template) | | Functions | | [std::swap(std::shared\_lock)](../thread/shared_lock/swap2 "cpp/thread/shared lock/swap2") (C++14) | specialization of `[std::swap](../algorithm/swap "cpp/algorithm/swap")` for `shared_lock` (function template) | ### Synopsis ``` namespace std { class shared_mutex; class shared_timed_mutex; template<class Mutex> class shared_lock; template<class Mutex> void swap(shared_lock<Mutex>& x, shared_lock<Mutex>& y) noexcept; } ``` #### Class `[std::shared\_mutex](../thread/shared_mutex "cpp/thread/shared mutex")` ``` namespace std { class shared_mutex { public: shared_mutex(); ~shared_mutex(); shared_mutex(const shared_mutex&) = delete; shared_mutex& operator=(const shared_mutex&) = delete; // exclusive ownership void lock(); // blocking bool try_lock(); void unlock(); // shared ownership void lock_shared(); // blocking bool try_lock_shared(); void unlock_shared(); using native_handle_type = /* implementation-defined */; native_handle_type native_handle(); }; } ``` #### Class `[std::shared\_timed\_mutex](../thread/shared_timed_mutex "cpp/thread/shared timed mutex")` ``` namespace std { class shared_timed_mutex { public: shared_timed_mutex(); ~shared_timed_mutex(); shared_timed_mutex(const shared_timed_mutex&) = delete; shared_timed_mutex& operator=(const shared_timed_mutex&) = delete; // exclusive ownership void lock(); // blocking bool try_lock(); template<class Rep, class Period> bool try_lock_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time); void unlock(); // shared ownership void lock_shared(); // blocking bool try_lock_shared(); template<class Rep, class Period> bool try_lock_shared_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_lock_shared_until(const chrono::time_point<Clock, Duration>& abs_time); void unlock_shared(); }; } ``` #### Class template `[std::shared\_lock](../thread/shared_lock "cpp/thread/shared lock")` ``` namespace std { template<class Mutex> class shared_lock { public: using mutex_type = Mutex; // construct/copy/destroy shared_lock() noexcept; explicit shared_lock(mutex_type& m); // blocking shared_lock(mutex_type& m, defer_lock_t) noexcept; shared_lock(mutex_type& m, try_to_lock_t); shared_lock(mutex_type& m, adopt_lock_t); template<class Clock, class Duration> shared_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time); template<class Rep, class Period> shared_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time); ~shared_lock(); shared_lock(const shared_lock&) = delete; shared_lock& operator=(const shared_lock&) = delete; shared_lock(shared_lock&& u) noexcept; shared_lock& operator=(shared_lock&& u) noexcept; // locking void lock(); // blocking bool try_lock(); template<class Rep, class Period> bool try_lock_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time); void unlock(); // modifiers void swap(shared_lock& u) noexcept; mutex_type* release() noexcept; // observers bool owns_lock() const noexcept; explicit operator bool () const noexcept; mutex_type* mutex() const noexcept; private: mutex_type* pm; // exposition only bool owns; // exposition only }; template<class Mutex> void swap(shared_lock<Mutex>& x, shared_lock<Mutex>& y) noexcept; } ``` cpp Standard library header <algorithm> Standard library header <algorithm> =================================== This header is part of the [algorithm](../algorithm "cpp/algorithm") library. | | | --- | | Includes | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | Defined in namespace `std::ranges` | | Return types (C++20) | | [ranges::in\_fun\_result](../algorithm/ranges/return_types/in_fun_result "cpp/algorithm/ranges/return types/in fun result") (C++20) | provides a way to store an iterator and a function object as a single unit (class template) | | [ranges::in\_in\_result](../algorithm/ranges/return_types/in_in_result "cpp/algorithm/ranges/return types/in in result") (C++20) | provides a way to store two iterators as a single unit (class template) | | [ranges::in\_out\_result](../algorithm/ranges/return_types/in_out_result "cpp/algorithm/ranges/return types/in out result") (C++20) | provides a way to store two iterators as a single unit (class template) | | [ranges::in\_in\_out\_result](../algorithm/ranges/return_types/in_in_out_result "cpp/algorithm/ranges/return types/in in out result") (C++20) | provides a way to store three iterators as a single unit (class template) | | [ranges::in\_out\_out\_result](../algorithm/ranges/return_types/in_out_out_result "cpp/algorithm/ranges/return types/in out out result") (C++20) | provides a way to store three iterators as a single unit (class template) | | [ranges::min\_max\_result](../algorithm/ranges/return_types/min_max_result "cpp/algorithm/ranges/return types/min max result") (C++20) | provides a way to store two objects or references of the same type as a single unit (class template) | | [ranges::in\_found\_result](../algorithm/ranges/return_types/in_found_result "cpp/algorithm/ranges/return types/in found result") (C++20) | provides a way to store an iterator and a boolean flag as a single unit (class template) | | [ranges::in\_value\_result](../algorithm/ranges/return_types/in_value_result "cpp/algorithm/ranges/return types/in value result") (C++23) | provides a way to store an iterator and a value as a single unit (class template) | | [ranges::out\_value\_result](../algorithm/ranges/return_types/out_value_result "cpp/algorithm/ranges/return types/out value result") (C++23) | provides a way to store an iterator and a value as a single unit (class template) | | Functions | | Non-modifying sequence operations | | [all\_ofany\_ofnone\_of](../algorithm/all_any_none_of "cpp/algorithm/all any none of") (C++11)(C++11)(C++11) | checks if a predicate is `true` for all, any or none of the elements in a range (function template) | | [for\_each](../algorithm/for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) | | [for\_each\_n](../algorithm/for_each_n "cpp/algorithm/for each n") (C++17) | applies a function object to the first n elements of a sequence (function template) | | [countcount\_if](../algorithm/count "cpp/algorithm/count") | returns the number of elements satisfying specific criteria (function template) | | [mismatch](../algorithm/mismatch "cpp/algorithm/mismatch") | finds the first position where two ranges differ (function template) | | [findfind\_iffind\_if\_not](../algorithm/find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [find\_end](../algorithm/find_end "cpp/algorithm/find end") | finds the last sequence of elements in a certain range (function template) | | [find\_first\_of](../algorithm/find_first_of "cpp/algorithm/find first of") | searches for any one of a set of elements (function template) | | [adjacent\_find](../algorithm/adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | | [search](../algorithm/search "cpp/algorithm/search") | searches for a range of elements (function template) | | [search\_n](../algorithm/search_n "cpp/algorithm/search n") | searches a range for a number of consecutive copies of an element (function template) | | Modifying sequence operations | | [copycopy\_if](../algorithm/copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [copy\_n](../algorithm/copy_n "cpp/algorithm/copy n") (C++11) | copies a number of elements to a new location (function template) | | [copy\_backward](../algorithm/copy_backward "cpp/algorithm/copy backward") | copies a range of elements in backwards order (function template) | | [move](../algorithm/move "cpp/algorithm/move") (C++11) | moves a range of elements to a new location (function template) | | [move\_backward](../algorithm/move_backward "cpp/algorithm/move backward") (C++11) | moves a range of elements to a new location in backwards order (function template) | | [fill](../algorithm/fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [fill\_n](../algorithm/fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) | | [transform](../algorithm/transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [generate](../algorithm/generate "cpp/algorithm/generate") | assigns the results of successive function calls to every element in a range (function template) | | [generate\_n](../algorithm/generate_n "cpp/algorithm/generate n") | assigns the results of successive function calls to N elements in a range (function template) | | [removeremove\_if](../algorithm/remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) | | [remove\_copyremove\_copy\_if](../algorithm/remove_copy "cpp/algorithm/remove copy") | copies a range of elements omitting those that satisfy specific criteria (function template) | | [replacereplace\_if](../algorithm/replace "cpp/algorithm/replace") | replaces all values satisfying specific criteria with another value (function template) | | [replace\_copyreplace\_copy\_if](../algorithm/replace_copy "cpp/algorithm/replace copy") | copies a range, replacing elements satisfying specific criteria with another value (function template) | | [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) | | [reverse](../algorithm/reverse "cpp/algorithm/reverse") | reverses the order of elements in a range (function template) | | [reverse\_copy](../algorithm/reverse_copy "cpp/algorithm/reverse copy") | creates a copy of a range that is reversed (function template) | | [rotate](../algorithm/rotate "cpp/algorithm/rotate") | rotates the order of elements in a range (function template) | | [rotate\_copy](../algorithm/rotate_copy "cpp/algorithm/rotate copy") | copies and rotate a range of elements (function template) | | [shift\_leftshift\_right](../algorithm/shift "cpp/algorithm/shift") (C++20) | shifts elements in a range (function template) | | [random\_shuffleshuffle](../algorithm/random_shuffle "cpp/algorithm/random shuffle") (until C++17)(C++11) | randomly re-orders elements in a range (function template) | | [sample](../algorithm/sample "cpp/algorithm/sample") (C++17) | selects n random elements from a sequence (function template) | | [unique](../algorithm/unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | | [unique\_copy](../algorithm/unique_copy "cpp/algorithm/unique copy") | creates a copy of some range of elements that contains no consecutive duplicates (function template) | | Partitioning operations | | [is\_partitioned](../algorithm/is_partitioned "cpp/algorithm/is partitioned") (C++11) | determines if the range is partitioned by the given predicate (function template) | | [partition](../algorithm/partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [partition\_copy](../algorithm/partition_copy "cpp/algorithm/partition copy") (C++11) | copies a range dividing the elements into two groups (function template) | | [stable\_partition](../algorithm/stable_partition "cpp/algorithm/stable partition") | divides elements into two groups while preserving their relative order (function template) | | [partition\_point](../algorithm/partition_point "cpp/algorithm/partition point") (C++11) | locates the partition point of a partitioned range (function template) | | Sorting operations | | [is\_sorted](../algorithm/is_sorted "cpp/algorithm/is sorted") (C++11) | checks whether a range is sorted into ascending order (function template) | | [is\_sorted\_until](../algorithm/is_sorted_until "cpp/algorithm/is sorted until") (C++11) | finds the largest sorted subrange (function template) | | [sort](../algorithm/sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [partial\_sort](../algorithm/partial_sort "cpp/algorithm/partial sort") | sorts the first N elements of a range (function template) | | [partial\_sort\_copy](../algorithm/partial_sort_copy "cpp/algorithm/partial sort copy") | copies and partially sorts a range of elements (function template) | | [stable\_sort](../algorithm/stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [nth\_element](../algorithm/nth_element "cpp/algorithm/nth element") | partially sorts the given range making sure that it is partitioned by the given element (function template) | | Binary search operations (on sorted ranges) | | [lower\_bound](../algorithm/lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | | [upper\_bound](../algorithm/upper_bound "cpp/algorithm/upper bound") | returns an iterator to the first element *greater* than a certain value (function template) | | [binary\_search](../algorithm/binary_search "cpp/algorithm/binary search") | determines if an element exists in a partially-ordered range (function template) | | [equal\_range](../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | | Other operations on sorted ranges | | [merge](../algorithm/merge "cpp/algorithm/merge") | merges two sorted ranges (function template) | | [inplace\_merge](../algorithm/inplace_merge "cpp/algorithm/inplace merge") | merges two ordered ranges in-place (function template) | | Set operations (on sorted ranges) | | [includes](../algorithm/includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [set\_difference](../algorithm/set_difference "cpp/algorithm/set difference") | computes the difference between two sets (function template) | | [set\_intersection](../algorithm/set_intersection "cpp/algorithm/set intersection") | computes the intersection of two sets (function template) | | [set\_symmetric\_difference](../algorithm/set_symmetric_difference "cpp/algorithm/set symmetric difference") | computes the symmetric difference between two sets (function template) | | [set\_union](../algorithm/set_union "cpp/algorithm/set union") | computes the union of two sets (function template) | | Heap operations | | [is\_heap](../algorithm/is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [is\_heap\_until](../algorithm/is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [make\_heap](../algorithm/make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [push\_heap](../algorithm/push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [pop\_heap](../algorithm/pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [sort\_heap](../algorithm/sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | Minimum/maximum operations | | [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) | | [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) | | [clamp](../algorithm/clamp "cpp/algorithm/clamp") (C++17) | clamps a value between a pair of boundary values (function template) | | Comparison operations | | [equal](../algorithm/equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [lexicographical\_compare](../algorithm/lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [lexicographical\_compare\_three\_way](../algorithm/lexicographical_compare_three_way "cpp/algorithm/lexicographical compare three way") (C++20) | compares two ranges using three-way comparison (function template) | | Permutation operations | | [is\_permutation](../algorithm/is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) | | [next\_permutation](../algorithm/next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](../algorithm/prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | Function-like entities (C++20) | | Defined in namespace `std::ranges` | | Non-modifying sequence operations | | [ranges::all\_ofranges::any\_ofranges::none\_of](../algorithm/ranges/all_any_none_of "cpp/algorithm/ranges/all any none of") (C++20)(C++20)(C++20) | checks if a predicate is `true` for all, any or none of the elements in a range (niebloid) | | [ranges::for\_each](../algorithm/ranges/for_each "cpp/algorithm/ranges/for each") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::for\_each\_n](../algorithm/ranges/for_each_n "cpp/algorithm/ranges/for each n") (C++20) | applies a function object to the first n elements of a sequence (niebloid) | | [ranges::countranges::count\_if](../algorithm/ranges/count "cpp/algorithm/ranges/count") (C++20)(C++20) | returns the number of elements satisfying specific criteria (niebloid) | | [ranges::mismatch](../algorithm/ranges/mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](../algorithm/ranges/find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::find\_lastranges::find\_last\_ifranges::find\_last\_if\_not](../algorithm/ranges/find_last "cpp/algorithm/ranges/find last") (C++23)(C++23)(C++23) | finds the last element satisfying specific criteria (niebloid) | | [ranges::find\_end](../algorithm/ranges/find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::find\_first\_of](../algorithm/ranges/find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | | [ranges::adjacent\_find](../algorithm/ranges/adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::search](../algorithm/ranges/search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::search\_n](../algorithm/ranges/search_n "cpp/algorithm/ranges/search n") (C++20) | searches for a number consecutive copies of an element in a range (niebloid) | | [ranges::containsranges::contains\_subrange](../algorithm/ranges/contains "cpp/algorithm/ranges/contains") (C++23)(C++23) | checks if the range contains the given element or subrange (niebloid) | | [ranges::starts\_with](../algorithm/ranges/starts_with "cpp/algorithm/ranges/starts with") (C++23) | checks whether a range starts with another range (niebloid) | | [ranges::ends\_with](../algorithm/ranges/ends_with "cpp/algorithm/ranges/ends with") (C++23) | checks whether a range ends with another range (niebloid) | | Modifying sequence operations | | [ranges::copyranges::copy\_if](../algorithm/ranges/copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_n](../algorithm/ranges/copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::copy\_backward](../algorithm/ranges/copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [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) | | [ranges::fill](../algorithm/ranges/fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [ranges::fill\_n](../algorithm/ranges/fill_n "cpp/algorithm/ranges/fill n") (C++20) | assigns a value to a number of elements (niebloid) | | [ranges::transform](../algorithm/ranges/transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::generate](../algorithm/ranges/generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::generate\_n](../algorithm/ranges/generate_n "cpp/algorithm/ranges/generate n") (C++20) | saves the result of N applications of a function (niebloid) | | [ranges::removeranges::remove\_if](../algorithm/ranges/remove "cpp/algorithm/ranges/remove") (C++20)(C++20) | removes elements satisfying specific criteria (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](../algorithm/ranges/remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [ranges::replaceranges::replace\_if](../algorithm/ranges/replace "cpp/algorithm/ranges/replace") (C++20)(C++20) | replaces all values satisfying specific criteria with another value (niebloid) | | [ranges::replace\_copyranges::replace\_copy\_if](../algorithm/ranges/replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [ranges::swap\_ranges](../algorithm/ranges/swap_ranges "cpp/algorithm/ranges/swap ranges") (C++20) | swaps two ranges of elements (niebloid) | | [ranges::reverse](../algorithm/ranges/reverse "cpp/algorithm/ranges/reverse") (C++20) | reverses the order of elements in a range (niebloid) | | [ranges::reverse\_copy](../algorithm/ranges/reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::rotate](../algorithm/ranges/rotate "cpp/algorithm/ranges/rotate") (C++20) | rotates the order of elements in a range (niebloid) | | [ranges::rotate\_copy](../algorithm/ranges/rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::shift\_leftranges::shift\_right](../algorithm/ranges/shift "cpp/algorithm/ranges/shift") (C++23) | shifts elements in a range (niebloid) | | [ranges::sample](../algorithm/ranges/sample "cpp/algorithm/ranges/sample") (C++20) | selects n random elements from a sequence (niebloid) | | [ranges::shuffle](../algorithm/ranges/shuffle "cpp/algorithm/ranges/shuffle") (C++20) | randomly re-orders elements in a range (niebloid) | | [ranges::unique](../algorithm/ranges/unique "cpp/algorithm/ranges/unique") (C++20) | removes consecutive duplicate elements in a range (niebloid) | | [ranges::unique\_copy](../algorithm/ranges/unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | Partitioning operations | | [ranges::is\_partitioned](../algorithm/ranges/is_partitioned "cpp/algorithm/ranges/is partitioned") (C++20) | determines if the range is partitioned by the given predicate (niebloid) | | [ranges::partition](../algorithm/ranges/partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::partition\_copy](../algorithm/ranges/partition_copy "cpp/algorithm/ranges/partition copy") (C++20) | copies a range dividing the 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) | | [ranges::partition\_point](../algorithm/ranges/partition_point "cpp/algorithm/ranges/partition point") (C++20) | locates the partition point of a partitioned range (niebloid) | | Sorting operations | | [ranges::is\_sorted](../algorithm/ranges/is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) | | [ranges::is\_sorted\_until](../algorithm/ranges/is_sorted_until "cpp/algorithm/ranges/is sorted until") (C++20) | finds the largest sorted subrange (niebloid) | | [ranges::sort](../algorithm/ranges/sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (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::partial\_sort\_copy](../algorithm/ranges/partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (C++20) | copies and partially sorts a range of elements (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::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) | | Binary search operations (on sorted ranges) | | [ranges::lower\_bound](../algorithm/ranges/lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | | [ranges::upper\_bound](../algorithm/ranges/upper_bound "cpp/algorithm/ranges/upper bound") (C++20) | returns an iterator to the first element *greater* than a certain value (niebloid) | | [ranges::binary\_search](../algorithm/ranges/binary_search "cpp/algorithm/ranges/binary search") (C++20) | determines if an element exists in a partially-ordered range (niebloid) | | [ranges::equal\_range](../algorithm/ranges/equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | | Other operations on sorted ranges | | [ranges::merge](../algorithm/ranges/merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::inplace\_merge](../algorithm/ranges/inplace_merge "cpp/algorithm/ranges/inplace merge") (C++20) | merges two ordered ranges in-place (niebloid) | | Set operations (on sorted ranges) | | [ranges::includes](../algorithm/ranges/includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [ranges::set\_difference](../algorithm/ranges/set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between 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\_symmetric\_difference](../algorithm/ranges/set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | | [ranges::set\_union](../algorithm/ranges/set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | Heap operations | | [ranges::is\_heap](../algorithm/ranges/is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::is\_heap\_until](../algorithm/ranges/is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is 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::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::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) | | Minimum/maximum operations | | [ranges::max](../algorithm/ranges/max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [ranges::max\_element](../algorithm/ranges/max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) | | [ranges::min](../algorithm/ranges/min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | | [ranges::min\_element](../algorithm/ranges/min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | | [ranges::minmax](../algorithm/ranges/minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | | [ranges::minmax\_element](../algorithm/ranges/minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | | [ranges::clamp](../algorithm/ranges/clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | | Comparison operations | | [ranges::equal](../algorithm/ranges/equal "cpp/algorithm/ranges/equal") (C++20) | determines if two sets of elements are the same (niebloid) | | [ranges::lexicographical\_compare](../algorithm/ranges/lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (C++20) | returns true if one range is lexicographically less than another (niebloid) | | Permutation operations | | [ranges::is\_permutation](../algorithm/ranges/is_permutation "cpp/algorithm/ranges/is permutation") (C++20) | determines if a sequence is a permutation of another sequence (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) | ### Synopsis ``` #include <initializer_list> namespace std { namespace ranges { // algorithm result types template<class I, class F> struct in_fun_result; template<class I1, class I2> struct in_in_result; template<class I, class O> struct in_out_result; template<class I1, class I2, class O> struct in_in_out_result; template<class I, class O1, class O2> struct in_out_out_result; template<class T> struct min_max_result; template<class I> struct in_found_result; template<class I, class T> struct in_value_result; template<class O, class T> struct out_value_result; } // non-modifying sequence operations // all of template<class InputIter, class Pred> constexpr bool all_of(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> bool all_of(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr bool all_of(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr bool all_of(R&& r, Pred pred, Proj proj = {}); } // any of template<class InputIter, class Pred> constexpr bool any_of(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> bool any_of(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr bool any_of(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr bool any_of(R&& r, Pred pred, Proj proj = {}); } // none of template<class InputIter, class Pred> constexpr bool none_of(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> bool none_of(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr bool none_of(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr bool none_of(R&& r, Pred pred, Proj proj = {}); } // contains namespace ranges { template<input_iterator I, sentinel_for<I> S, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr bool contains(I first, S last, const T& value, Proj proj = {}); template<input_range R, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr bool contains(R&& r, const T& value, Proj proj = {}); template<forward_iterator I1, sentinel_for<I1> S1, forward_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool contains_subrange(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<forward_range R1, forward_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool contains_subrange(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // for each template<class InputIter, class Function> constexpr Function for_each(InputIter first, InputIter last, Function f); template<class ExecutionPolicy, class ForwardIter, class Function> void for_each(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Function f); namespace ranges { template<class I, class F> using for_each_result = in_fun_result<I, F>; template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirectly_unary_invocable<projected<I, Proj>> Fun> constexpr for_each_result<I, Fun> for_each(I first, S last, Fun f, Proj proj = {}); template<input_range R, class Proj = identity, indirectly_unary_invocable<projected<iterator_t<R>, Proj>> Fun> constexpr for_each_result<borrowed_iterator_t<R>, Fun> for_each(R&& r, Fun f, Proj proj = {}); } template<class InputIter, class Size, class Function> constexpr InputIter for_each_n(InputIter first, Size n, Function f); template<class ExecutionPolicy, class ForwardIter, class Size, class Function> ForwardIter for_each_n(ExecutionPolicy&& exec, ForwardIter first, Size n, Function f); namespace ranges { template<class I, class F> using for_each_n_result = in_fun_result<I, F>; template<input_iterator I, class Proj = identity, indirectly_unary_invocable<projected<I, Proj>> Fun> constexpr for_each_n_result<I, Fun> for_each_n(I first, iter_difference_t<I> n, Fun f, Proj proj = {}); } // find template<class InputIter, class T> constexpr InputIter find(InputIter first, InputIter last, const T& value); template<class ExecutionPolicy, class ForwardIter, class T> ForwardIter find(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, const T& value); template<class InputIter, class Pred> constexpr InputIter find_if(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> ForwardIter find_if(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); template<class InputIter, class Pred> constexpr InputIter find_if_not(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> ForwardIter find_if_not(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<input_iterator I, sentinel_for<I> S, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr I find(I first, S last, const T& value, Proj proj = {}); template<input_range R, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr borrowed_iterator_t<R> find(R&& r, const T& value, Proj proj = {}); template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr I find_if(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr borrowed_iterator_t<R> find_if(R&& r, Pred pred, Proj proj = {}); template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr I find_if_not(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr borrowed_iterator_t<R> find_if_not(R&& r, Pred pred, Proj proj = {}); } // find last namespace ranges { template<forward_iterator I, sentinel_for<I> S, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr subrange<I> find_last(I first, S last, const T& value, Proj proj = {}); template<forward_range R, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr borrowed_subrange_t<R> find_last(R&& r, const T& value, Proj proj = {}); template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr subrange<I> find_last_if(I first, S last, Pred pred, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr borrowed_subrange_t<R> find_last_if(R&& r, Pred pred, Proj proj = {}); template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr subrange<I> find_last_if_not(I first, S last, Pred pred, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr borrowed_subrange_t<R> find_last_if_not(R&& r, Pred pred, Proj proj = {}); } // find end template<class ForwardIter1, class ForwardIter2> constexpr ForwardIter1 find_end(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ForwardIter1, class ForwardIter2, class BinaryPred> constexpr ForwardIter1 find_end(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter1 find_end(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> ForwardIter1 find_end(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); namespace ranges { template<forward_iterator I1, sentinel_for<I1> S1, forward_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr subrange<I1> find_end(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<forward_range R1, forward_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr borrowed_subrange_t<R1> find_end(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // find first template<class InputIter, class ForwardIter> constexpr InputIter find_first_of(InputIter first1, InputIter last1, ForwardIter first2, ForwardIter last2); template<class InputIter, class ForwardIter, class BinaryPred> constexpr InputIter find_first_of(InputIter first1, InputIter last1, ForwardIter first2, ForwardIter last2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter1 find_first_of(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> ForwardIter1 find_first_of(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); namespace ranges { template<input_iterator I1, sentinel_for<I1> S1, forward_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr I1 find_first_of(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, forward_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr borrowed_iterator_t<R1> find_first_of(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // adjacent find template<class ForwardIter> constexpr ForwardIter adjacent_find(ForwardIter first, ForwardIter last); template<class ForwardIter, class BinaryPred> constexpr ForwardIter adjacent_find(ForwardIter first, ForwardIter last, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter> ForwardIter adjacent_find(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class BinaryPred> ForwardIter adjacent_find(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, BinaryPred pred); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_binary_predicate<projected<I, Proj>, projected<I, Proj>> Pred = ranges::equal_to> constexpr I adjacent_find(I first, S last, Pred pred = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_binary_predicate<projected<iterator_t<R>, Proj>, projected<iterator_t<R>, Proj>> Pred = ranges::equal_to> constexpr borrowed_iterator_t<R> adjacent_find(R&& r, Pred pred = {}, Proj proj = {}); } // count template<class InputIter, class T> constexpr typename iterator_traits<InputIter>::difference_type count(InputIter first, InputIter last, const T& value); template<class ExecutionPolicy, class ForwardIter, class T> typename iterator_traits<ForwardIter>::difference_type count(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, const T& value); template<class InputIter, class Pred> constexpr typename iterator_traits<InputIter>::difference_type count_if(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> typename iterator_traits<ForwardIter>::difference_type count_if(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<input_iterator I, sentinel_for<I> S, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr iter_difference_t<I> count(I first, S last, const T& value, Proj proj = {}); template<input_range R, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr range_difference_t<R> count(R&& r, const T& value, Proj proj = {}); template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr iter_difference_t<I> count_if(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr range_difference_t<R> count_if(R&& r, Pred pred, Proj proj = {}); } // mismatch template<class InputIter1, class InputIter2> constexpr pair<InputIter1, InputIter2> mismatch(InputIter1 first1, InputIter1 last1, InputIter2 first2); template<class InputIter1, class InputIter2, class BinaryPred> constexpr pair<InputIter1, InputIter2> mismatch(InputIter1 first1, InputIter1 last1, InputIter2 first2, BinaryPred pred); template<class InputIter1, class InputIter2> constexpr pair<InputIter1, InputIter2> mismatch(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2); template<class InputIter1, class InputIter2, class BinaryPred> constexpr pair<InputIter1, InputIter2> mismatch(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> pair<ForwardIter1, ForwardIter2> mismatch(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> pair<ForwardIter1, ForwardIter2> mismatch(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> pair<ForwardIter1, ForwardIter2> mismatch(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> pair<ForwardIter1, ForwardIter2> mismatch(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); namespace ranges { template<class I1, class I2> using mismatch_result = in_in_result<I1, I2>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr mismatch_result<I1, I2> mismatch(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr mismatch_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>> mismatch(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // equal template<class InputIter1, class InputIter2> constexpr bool equal(InputIter1 first1, InputIter1 last1, InputIter2 first2); template<class InputIter1, class InputIter2, class BinaryPred> constexpr bool equal(InputIter1 first1, InputIter1 last1, InputIter2 first2, BinaryPred pred); template<class InputIter1, class InputIter2> constexpr bool equal(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2); template<class InputIter1, class InputIter2, class BinaryPred> constexpr bool equal(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> bool equal(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> bool equal(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> bool equal(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> bool equal(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); namespace ranges { template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool equal(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool equal(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // is permutation template<class ForwardIter1, class ForwardIter2> constexpr bool is_permutation(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2); template<class ForwardIter1, class ForwardIter2, class BinaryPred> constexpr bool is_permutation(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, BinaryPred pred); template<class ForwardIter1, class ForwardIter2> constexpr bool is_permutation(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ForwardIter1, class ForwardIter2, class BinaryPred> constexpr bool is_permutation(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); namespace ranges { template<forward_iterator I1, sentinel_for<I1> S1, forward_iterator I2, sentinel_for<I2> S2, class Proj1 = identity, class Proj2 = identity, indirect_equivalence_relation<projected<I1, Proj1>, projected<I2, Proj2>> Pred = ranges::equal_to> constexpr bool is_permutation(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<forward_range R1, forward_range R2, class Proj1 = identity, class Proj2 = identity, indirect_equivalence_relation<projected<iterator_t<R1>, Proj1>, projected<iterator_t<R2>, Proj2>> Pred = ranges::equal_to> constexpr bool is_permutation(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // search template<class ForwardIter1, class ForwardIter2> constexpr ForwardIter1 search(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ForwardIter1, class ForwardIter2, class BinaryPred> constexpr ForwardIter1 search(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter1 search(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> ForwardIter1 search(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, BinaryPred pred); namespace ranges { template<forward_iterator I1, sentinel_for<I1> S1, forward_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr subrange<I1> search(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<forward_range R1, forward_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr borrowed_subrange_t<R1> search(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class ForwardIter, class Size, class T> constexpr ForwardIter search_n(ForwardIter first, ForwardIter last, Size count, const T& value); template<class ForwardIter, class Size, class T, class BinaryPred> constexpr ForwardIter search_n(ForwardIter first, ForwardIter last, Size count, const T& value, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter, class Size, class T> ForwardIter search_n(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Size count, const T& value); template<class ExecutionPolicy, class ForwardIter, class Size, class T, class BinaryPred> ForwardIter search_n(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Size count, const T& value, BinaryPred pred); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class T, class Pred = ranges::equal_to, class Proj = identity> requires indirectly_comparable<I, const T*, Pred, Proj> constexpr subrange<I> search_n(I first, S last, iter_difference_t<I> count, const T& value, Pred pred = {}, Proj proj = {}); template<forward_range R, class T, class Pred = ranges::equal_to, class Proj = identity> requires indirectly_comparable<iterator_t<R>, const T*, Pred, Proj> constexpr borrowed_subrange_t<R> search_n(R&& r, range_difference_t<R> count, const T& value, Pred pred = {}, Proj proj = {}); } template<class ForwardIter, class Searcher> constexpr ForwardIter search(ForwardIter first, ForwardIter last, const Searcher& searcher); namespace ranges { // starts with template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool starts_with(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool starts_with(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); // ends with template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires (forward_iterator<I1> || sized_sentinel_for<S1, I1>) && (forward_iterator<I2> || sized_sentinel_for<S2, I2>) && indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool ends_with(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, class Pred = ranges::equal_to, class Proj1 = identity, class Proj2 = identity> requires (forward_range<R1> || sized_range<R1>) && (forward_range<R2> || sized_range<R2>) && indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool ends_with(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); // fold template<class F> class flipped { // exposition only F f; // exposition only public: template<class T, class U> requires invocable<F&, U, T> invoke_result_t<F&, U, T> operator()(T&&, U&&); }; template<class F, class T, class I, class U> concept /*indirectly-binary-left-foldable-impl*/ = // exposition only movable<T> && movable<U> && convertible_to<T, U> && invocable<F&, U, iter_reference_t<I>> && assignable_from<U&, invoke_result_t<F&, U, iter_reference_t<I>>>; template<class F, class T, class I> concept /*indirectly-binary-left-foldable*/ = // exposition only copy_constructible<F> && indirectly_readable<I> && invocable<F&, T, iter_reference_t<I>> && convertible_to<invoke_result_t<F&, T, iter_reference_t<I>>, decay_t<invoke_result_t<F&, T, iter_reference_t<I>>>> && /*indirectly-binary-left-foldable-impl*/<F, T, I, decay_t<invoke_result_t<F&, T, iter_reference_t<I>>>>; template<class F, class T, class I> concept /*indirectly-binary-right-foldable*/ = // exposition only /*indirectly-binary-left-foldable*/<flipped<F>, T, I>; template<input_iterator I, sentinel_for<I> S, class T, /*indirectly-binary-left-foldable*/<T, I> F> constexpr auto fold_left(I first, S last, T init, F f); template<input_range R, class T, /*indirectly-binary-left-foldable*/<T, iterator_t<R>> F> constexpr auto fold_left(R&& r, T init, F f); template<input_iterator I, sentinel_for<I> S, /*indirectly-binary-left-foldable*/<iter_value_t<I>, I> F> requires constructible_from<iter_value_t<I>, iter_reference_t<I>> constexpr auto fold_left_first(I first, S last, F f); template<input_range R, /*indirectly-binary-left-foldable*/<range_value_t<R>, iterator_t<R>> F> requires constructible_from<range_value_t<R>, range_reference_t<R>> constexpr auto fold_left_first(R&& r, F f); template<bidirectional_iterator I, sentinel_for<I> S, class T, /*indirectly-binary-right-foldable*/<T, I> F> constexpr auto fold_right(I first, S last, T init, F f); template<bidirectional_range R, class T, /*indirectly-binary-right-foldable*/<T, iterator_t<R>> F> constexpr auto fold_right(R&& r, T init, F f); template <bidirectional_iterator I, sentinel_for<I> S, /*indirectly-binary-right-foldable*/<iter_value_t<I>, I> F> requires constructible_from<iter_value_t<I>, iter_reference_t<I>> constexpr auto fold_right_last(I first, S last, F f); template<bidirectional_range R, /*indirectly-binary-right-foldable*/<range_value_t<R>, iterator_t<R>> F> requires constructible_from<range_value_t<R>, range_reference_t<R>> constexpr auto fold_right_last(R&& r, F f); template<class I, class T> using fold_left_with_iter_result = in_value_result<I, T>; template<class I, class T> using fold_left_first_with_iter_result = in_value_result<I, T>; template<input_iterator I, sentinel_for<I> S, class T, /*indirectly-binary-left-foldable*/<T, I> F> constexpr /* see description */ fold_left_with_iter(I first, S last, T init, F f); template<input_range R, class T, /*indirectly-binary-left-foldable*/<T, iterator_t<R>> F> constexpr /* see description */ fold_left_with_iter(R&& r, T init, F f); template<input_iterator I, sentinel_for<I> S, /*indirectly-binary-left-foldable*/<iter_value_t<I>, I> F> requires constructible_from<iter_value_t<I>, iter_reference_t<I>> constexpr /* see description */ fold_left_first_with_iter(I first, S last, F f); template<input_range R, /*indirectly-binary-left-foldable*/<range_value_t<R>, iterator_t<R>> F> requires constructible_from<range_value_t<R>, range_reference_t<R>> constexpr /* see description */ fold_left_first_with_iter(R&& r, F f); } // mutating sequence operations // copy template<class InputIter, class OutputIter> constexpr OutputIter copy(InputIter first, InputIter last, OutputIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter2 copy(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result); namespace ranges { template<class I, class O> using copy_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O> requires indirectly_copyable<I, O> constexpr copy_result<I, O> copy(I first, S last, O result); template<input_range R, weakly_incrementable O> requires indirectly_copyable<iterator_t<R>, O> constexpr copy_result<borrowed_iterator_t<R>, O> copy(R&& r, O result); } template<class InputIter, class Size, class OutputIter> constexpr OutputIter copy_n(InputIter first, Size n, OutputIter result); template<class ExecutionPolicy, class ForwardIter1, class Size, class ForwardIter2> ForwardIter2 copy_n(ExecutionPolicy&& exec, ForwardIter1 first, Size n, ForwardIter2 result); namespace ranges { template<class I, class O> using copy_n_result = in_out_result<I, O>; template<input_iterator I, weakly_incrementable O> requires indirectly_copyable<I, O> constexpr copy_n_result<I, O> copy_n(I first, iter_difference_t<I> n, O result); } template<class InputIter, class OutputIter, class Pred> constexpr OutputIter copy_if(InputIter first, InputIter last, OutputIter result, Pred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class Pred> ForwardIter2 copy_if(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result, Pred pred); namespace ranges { template<class I, class O> using copy_if_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> requires indirectly_copyable<I, O> constexpr copy_if_result<I, O> copy_if(I first, S last, O result, Pred pred, Proj proj = {}); template<input_range R, weakly_incrementable O, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires indirectly_copyable<iterator_t<R>, O> constexpr copy_if_result<borrowed_iterator_t<R>, O> copy_if(R&& r, O result, Pred pred, Proj proj = {}); } template<class BidirectionalIter1, class BidirectionalIter2> constexpr BidirectionalIter2 copy_backward(BidirectionalIter1 first, BidirectionalIter1 last, BidirectionalIter2 result); namespace ranges { template<class I1, class I2> using copy_backward_result = in_out_result<I1, I2>; template<bidirectional_iterator I1, sentinel_for<I1> S1, bidirectional_iterator I2> requires indirectly_copyable<I1, I2> constexpr copy_backward_result<I1, I2> copy_backward(I1 first, S1 last, I2 result); template<bidirectional_range R, bidirectional_iterator I> requires indirectly_copyable<iterator_t<R>, I> constexpr copy_backward_result<borrowed_iterator_t<R>, I> copy_backward(R&& r, I result); } // move template<class InputIter, class OutputIter> constexpr OutputIter move(InputIter first, InputIter last, OutputIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter2 move(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result); namespace ranges { template<class I, class O> using move_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O> requires indirectly_movable<I, O> constexpr move_result<I, O> move(I first, S last, O result); template<input_range R, weakly_incrementable O> requires indirectly_movable<iterator_t<R>, O> constexpr move_result<borrowed_iterator_t<R>, O> move(R&& r, O result); } template<class BidirectionalIter1, class BidirectionalIter2> constexpr BidirectionalIter2 move_backward(BidirectionalIter1 first, BidirectionalIter1 last, BidirectionalIter2 result); namespace ranges { template<class I1, class I2> using move_backward_result = in_out_result<I1, I2>; template<bidirectional_iterator I1, sentinel_for<I1> S1, bidirectional_iterator I2> requires indirectly_movable<I1, I2> constexpr move_backward_result<I1, I2> move_backward(I1 first, S1 last, I2 result); template<bidirectional_range R, bidirectional_iterator I> requires indirectly_movable<iterator_t<R>, I> constexpr move_backward_result<borrowed_iterator_t<R>, I> move_backward(R&& r, I result); } // swap template<class ForwardIter1, class ForwardIter2> constexpr ForwardIter2 swap_ranges(ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter2 swap_ranges(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2); namespace ranges { template<class I1, class I2> using swap_ranges_result = in_in_result<I1, I2>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2> requires indirectly_swappable<I1, I2> constexpr swap_ranges_result<I1, I2> swap_ranges(I1 first1, S1 last1, I2 first2, S2 last2); template<input_range R1, input_range R2> requires indirectly_swappable<iterator_t<R1>, iterator_t<R2>> constexpr swap_ranges_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>> swap_ranges(R1&& r1, R2&& r2); } template<class ForwardIter1, class ForwardIter2> constexpr void iter_swap(ForwardIter1 a, ForwardIter2 b); // transform template<class InputIter, class OutputIter, class UnaryOperation> constexpr OutputIter transform(InputIter first1, InputIter last1, OutputIter result, UnaryOperation op); template<class InputIter1, class InputIter2, class OutputIter, class BinaryOperation> constexpr OutputIter transform(InputIter1 first1, InputIter1 last1, InputIter2 first2, OutputIter result, BinaryOperation binary_op); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class UnaryOperation> ForwardIter2 transform(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 result, UnaryOperation op); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter, class BinaryOperation> ForwardIter transform(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter result, BinaryOperation binary_op); namespace ranges { template<class I, class O> using unary_transform_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, copy_constructible F, class Proj = identity> requires indirectly_writable<O, indirect_result_t<F&, projected<I, Proj>>> constexpr unary_transform_result<I, O> transform(I first1, S last1, O result, F op, Proj proj = {}); template<input_range R, weakly_incrementable O, copy_constructible F, class Proj = identity> requires indirectly_writable<O, indirect_result_t<F&, projected<iterator_t<R>, Proj>>> constexpr unary_transform_result<borrowed_iterator_t<R>, O> transform(R&& r, O result, F op, Proj proj = {}); template<class I1, class I2, class O> using binary_transform_result = in_in_out_result<I1, I2, O>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, weakly_incrementable O, copy_constructible F, class Proj1 = identity, class Proj2 = identity> requires indirectly_writable<O, indirect_result_t<F&, projected<I1, Proj1>, projected<I2, Proj2>>> constexpr binary_transform_result<I1, I2, O> transform(I1 first1, S1 last1, I2 first2, S2 last2, O result, F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, weakly_incrementable O, copy_constructible F, class Proj1 = identity, class Proj2 = identity> requires indirectly_writable<O, indirect_result_t<F&, projected<iterator_t<R1>, Proj1>, projected<iterator_t<R2>, Proj2>>> constexpr binary_transform_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O> transform(R1&& r1, R2&& r2, O result, F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {}); } // replace template<class ForwardIter, class T> constexpr void replace(ForwardIter first, ForwardIter last, const T& old_value, const T& new_value); template<class ExecutionPolicy, class ForwardIter, class T> void replace(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, const T& old_value, const T& new_value); template<class ForwardIter, class Pred, class T> constexpr void replace_if(ForwardIter first, ForwardIter last, Pred pred, const T& new_value); template<class ExecutionPolicy, class ForwardIter, class Pred, class T> void replace_if(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred, const T& new_value); namespace ranges { template<input_iterator I, sentinel_for<I> S, class T1, class T2, class Proj = identity> requires indirectly_writable<I, const T2&> && indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T1*> constexpr I replace(I first, S last, const T1& old_value, const T2& new_value, Proj proj = {}); template<input_range R, class T1, class T2, class Proj = identity> requires indirectly_writable<iterator_t<R>, const T2&> && indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T1*> constexpr borrowed_iterator_t<R> replace(R&& r, const T1& old_value, const T2& new_value, Proj proj = {}); template<input_iterator I, sentinel_for<I> S, class T, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> requires indirectly_writable<I, const T&> constexpr I replace_if(I first, S last, Pred pred, const T& new_value, Proj proj = {}); template<input_range R, class T, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires indirectly_writable<iterator_t<R>, const T&> constexpr borrowed_iterator_t<R> replace_if(R&& r, Pred pred, const T& new_value, Proj proj = {}); } template<class InputIter, class OutputIter, class T> constexpr OutputIter replace_copy(InputIter first, InputIter last, OutputIter result, const T& old_value, const T& new_value); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class T> ForwardIter2 replace_copy(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result, const T& old_value, const T& new_value); template<class InputIter, class OutputIter, class Pred, class T> constexpr OutputIter replace_copy_if(InputIter first, InputIter last, OutputIter result, Pred pred, const T& new_value); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class Pred, class T> ForwardIter2 replace_copy_if(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result, Pred pred, const T& new_value); namespace ranges { template<class I, class O> using replace_copy_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, class T1, class T2, output_iterator<const T2&> O, class Proj = identity> requires indirectly_copyable<I, O> && indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T1*> constexpr replace_copy_result<I, O> replace_copy(I first, S last, O result, const T1& old_value, const T2& new_value, Proj proj = {}); template<input_range R, class T1, class T2, output_iterator<const T2&> O, class Proj = identity> requires indirectly_copyable<iterator_t<R>, O> && indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T1*> constexpr replace_copy_result<borrowed_iterator_t<R>, O> replace_copy(R&& r, O result, const T1& old_value, const T2& new_value, Proj proj = {}); template<class I, class O> using replace_copy_if_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, class T, output_iterator<const T&> O, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> requires indirectly_copyable<I, O> constexpr replace_copy_if_result<I, O> replace_copy_if(I first, S last, O result, Pred pred, const T& new_value, Proj proj = {}); template<input_range R, class T, output_iterator<const T&> O, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires indirectly_copyable<iterator_t<R>, O> constexpr replace_copy_if_result<borrowed_iterator_t<R>, O> replace_copy_if(R&& r, O result, Pred pred, const T& new_value, Proj proj = {}); } // fill template<class ForwardIter, class T> constexpr void fill(ForwardIter first, ForwardIter last, const T& value); template<class ExecutionPolicy, class ForwardIter, class T> void fill(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, const T& value); template<class OutputIter, class Size, class T> constexpr OutputIter fill_n(OutputIter first, Size n, const T& value); template<class ExecutionPolicy, class ForwardIter, class Size, class T> ForwardIter fill_n(ExecutionPolicy&& exec, ForwardIter first, Size n, const T& value); namespace ranges { template<class T, output_iterator<const T&> O, sentinel_for<O> S> constexpr O fill(O first, S last, const T& value); template<class T, output_range<const T&> R> constexpr borrowed_iterator_t<R> fill(R&& r, const T& value); template<class T, output_iterator<const T&> O> constexpr O fill_n(O first, iter_difference_t<O> n, const T& value); } // generate template<class ForwardIter, class Generator> constexpr void generate(ForwardIter first, ForwardIter last, Generator gen); template<class ExecutionPolicy, class ForwardIter, class Generator> void generate(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Generator gen); template<class OutputIter, class Size, class Generator> constexpr OutputIter generate_n(OutputIter first, Size n, Generator gen); template<class ExecutionPolicy, class ForwardIter, class Size, class Generator> ForwardIter generate_n(ExecutionPolicy&& exec, ForwardIter first, Size n, Generator gen); namespace ranges { template<input_or_output_iterator O, sentinel_for<O> S, copy_constructible F> requires invocable<F&> && indirectly_writable<O, invoke_result_t<F&>> constexpr O generate(O first, S last, F gen); template<class R, copy_constructible F> requires invocable<F&> && output_range<R, invoke_result_t<F&>> constexpr borrowed_iterator_t<R> generate(R&& r, F gen); template<input_or_output_iterator O, copy_constructible F> requires invocable<F&> && indirectly_writable<O, invoke_result_t<F&>> constexpr O generate_n(O first, iter_difference_t<O> n, F gen); } // remove template<class ForwardIter, class T> constexpr ForwardIter remove(ForwardIter first, ForwardIter last, const T& value); template<class ExecutionPolicy, class ForwardIter, class T> ForwardIter remove(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, const T& value); template<class ForwardIter, class Pred> constexpr ForwardIter remove_if(ForwardIter first, ForwardIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> ForwardIter remove_if(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<permutable I, sentinel_for<I> S, class T, class Proj = identity> requires indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr subrange<I> remove(I first, S last, const T& value, Proj proj = {}); template<forward_range R, class T, class Proj = identity> requires permutable<iterator_t<R>> && indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr borrowed_subrange_t<R> remove(R&& r, const T& value, Proj proj = {}); template<permutable I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr subrange<I> remove_if(I first, S last, Pred pred, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires permutable<iterator_t<R>> constexpr borrowed_subrange_t<R> remove_if(R&& r, Pred pred, Proj proj = {}); } template<class InputIter, class OutputIter, class T> constexpr OutputIter remove_copy(InputIter first, InputIter last, OutputIter result, const T& value); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class T> ForwardIter2 remove_copy(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result, const T& value); template<class InputIter, class OutputIter, class Pred> constexpr OutputIter remove_copy_if(InputIter first, InputIter last, OutputIter result, Pred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class Pred> ForwardIter2 remove_copy_if(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result, Pred pred); namespace ranges { template<class I, class O> using remove_copy_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, class T, class Proj = identity> requires indirectly_copyable<I, O> && indirect_binary_predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr remove_copy_result<I, O> remove_copy(I first, S last, O result, const T& value, Proj proj = {}); template<input_range R, weakly_incrementable O, class T, class Proj = identity> requires indirectly_copyable<iterator_t<R>, O> && indirect_binary_predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr remove_copy_result<borrowed_iterator_t<R>, O> remove_copy(R&& r, O result, const T& value, Proj proj = {}); template<class I, class O> using remove_copy_if_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> requires indirectly_copyable<I, O> constexpr remove_copy_if_result<I, O> remove_copy_if(I first, S last, O result, Pred pred, Proj proj = {}); template<input_range R, weakly_incrementable O, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires indirectly_copyable<iterator_t<R>, O> constexpr remove_copy_if_result<borrowed_iterator_t<R>, O> remove_copy_if(R&& r, O result, Pred pred, Proj proj = {}); } // unique template<class ForwardIter> constexpr ForwardIter unique(ForwardIter first, ForwardIter last); template<class ForwardIter, class BinaryPred> constexpr ForwardIter unique(ForwardIter first, ForwardIter last, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter> ForwardIter unique(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class BinaryPred> ForwardIter unique(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, BinaryPred pred); namespace ranges { template<permutable I, sentinel_for<I> S, class Proj = identity, indirect_equivalence_relation<projected<I, Proj>> C = ranges::equal_to> constexpr subrange<I> unique(I first, S last, C comp = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_equivalence_relation<projected<iterator_t<R>, Proj>> C = ranges::equal_to> requires permutable<iterator_t<R>> constexpr borrowed_subrange_t<R> unique(R&& r, C comp = {}, Proj proj = {}); } template<class InputIter, class OutputIter> constexpr OutputIter unique_copy(InputIter first, InputIter last, OutputIter result); template<class InputIter, class OutputIter, class BinaryPred> constexpr OutputIter unique_copy(InputIter first, InputIter last, OutputIter result, BinaryPred pred); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter2 unique_copy(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class BinaryPred> ForwardIter2 unique_copy(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 last, ForwardIter2 result, BinaryPred pred); namespace ranges { template<class I, class O> using unique_copy_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, class Proj = identity, indirect_equivalence_relation<projected<I, Proj>> C = ranges::equal_to> requires indirectly_copyable<I, O> && (forward_iterator<I> || (input_iterator<O> && same_as<iter_value_t<I>, iter_value_t<O>>) || indirectly_copyable_storable<I, O>) constexpr unique_copy_result<I, O> unique_copy(I first, S last, O result, C comp = {}, Proj proj = {}); template<input_range R, weakly_incrementable O, class Proj = identity, indirect_equivalence_relation<projected<iterator_t<R>, Proj>> C = ranges::equal_to> requires indirectly_copyable<iterator_t<R>, O> && (forward_iterator<iterator_t<R>> || (input_iterator<O> && same_as<range_value_t<R>, iter_value_t<O>>) || indirectly_copyable_storable<iterator_t<R>, O>) constexpr unique_copy_result<borrowed_iterator_t<R>, O> unique_copy(R&& r, O result, C comp = {}, Proj proj = {}); } // reverse template<class BidirectionalIter> constexpr void reverse(BidirectionalIter first, BidirectionalIter last); template<class ExecutionPolicy, class BidirectionalIter> void reverse(ExecutionPolicy&& exec, BidirectionalIter first, BidirectionalIter last); namespace ranges { template<bidirectional_iterator I, sentinel_for<I> S> requires permutable<I> constexpr I reverse(I first, S last); template<bidirectional_range R> requires permutable<iterator_t<R>> constexpr borrowed_iterator_t<R> reverse(R&& r); } template<class BidirectionalIter, class OutputIter> constexpr OutputIter reverse_copy(BidirectionalIter first, BidirectionalIter last, OutputIter result); template<class ExecutionPolicy, class BidirectionalIter, class ForwardIter> ForwardIter reverse_copy(ExecutionPolicy&& exec, BidirectionalIter first, BidirectionalIter last, ForwardIter result); namespace ranges { template<class I, class O> using reverse_copy_result = in_out_result<I, O>; template<bidirectional_iterator I, sentinel_for<I> S, weakly_incrementable O> requires indirectly_copyable<I, O> constexpr reverse_copy_result<I, O> reverse_copy(I first, S last, O result); template<bidirectional_range R, weakly_incrementable O> requires indirectly_copyable<iterator_t<R>, O> constexpr reverse_copy_result<borrowed_iterator_t<R>, O> reverse_copy(R&& r, O result); } // rotate template<class ForwardIter> constexpr ForwardIter rotate(ForwardIter first, ForwardIter middle, ForwardIter last); template<class ExecutionPolicy, class ForwardIter> ForwardIter rotate(ExecutionPolicy&& exec, ForwardIter first, ForwardIter middle, ForwardIter last); namespace ranges { template<permutable I, sentinel_for<I> S> constexpr subrange<I> rotate(I first, I middle, S last); template<forward_range R> requires permutable<iterator_t<R>> constexpr borrowed_subrange_t<R> rotate(R&& r, iterator_t<R> middle); } template<class ForwardIter, class OutputIter> constexpr OutputIter rotate_copy(ForwardIter first, ForwardIter middle, ForwardIter last, OutputIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> ForwardIter2 rotate_copy(ExecutionPolicy&& exec, ForwardIter1 first, ForwardIter1 middle, ForwardIter1 last, ForwardIter2 result); namespace ranges { template<class I, class O> using rotate_copy_result = in_out_result<I, O>; template<forward_iterator I, sentinel_for<I> S, weakly_incrementable O> requires indirectly_copyable<I, O> constexpr rotate_copy_result<I, O> rotate_copy(I first, I middle, S last, O result); template<forward_range R, weakly_incrementable O> requires indirectly_copyable<iterator_t<R>, O> constexpr rotate_copy_result<borrowed_iterator_t<R>, O> rotate_copy(R&& r, iterator_t<R> middle, O result); } // sample template<class PopulationIter, class SampleIter, class Distance, class UniformRandomBitGenerator> SampleIter sample(PopulationIter first, PopulationIter last, SampleIter out, Distance n, UniformRandomBitGenerator&& g); namespace ranges { template<input_iterator I, sentinel_for<I> S, weakly_incrementable O, class Gen> requires (forward_iterator<I> || random_access_iterator<O>) && indirectly_copyable<I, O> && uniform_random_bit_generator<remove_reference_t<Gen>> O sample(I first, S last, O out, iter_difference_t<I> n, Gen&& g); template<input_range R, weakly_incrementable O, class Gen> requires (forward_range<R> || random_access_iterator<O>) && indirectly_copyable<iterator_t<R>, O> && uniform_random_bit_generator<remove_reference_t<Gen>> O sample(R&& r, O out, range_difference_t<R> n, Gen&& g); } // shuffle template<class RandomAccessIter, class UniformRandomBitGenerator> void shuffle(RandomAccessIter first, RandomAccessIter last, UniformRandomBitGenerator&& g); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Gen> requires permutable<I> && uniform_random_bit_generator<remove_reference_t<Gen>> I shuffle(I first, S last, Gen&& g); template<random_access_range R, class Gen> requires permutable<iterator_t<R>> && uniform_random_bit_generator<remove_reference_t<Gen>> borrowed_iterator_t<R> shuffle(R&& r, Gen&& g); } // shift template<class ForwardIter> constexpr ForwardIter shift_left(ForwardIter first, ForwardIter last, typename iterator_traits<ForwardIter>::difference_type n); template<class ExecutionPolicy, class ForwardIter> ForwardIter shift_left(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, typename iterator_traits<ForwardIter>::difference_type n); namespace ranges { template<permutable I, sentinel_for<I> S> constexpr subrange<I> shift_left(I first, S last, iter_difference_t<I> n); template<forward_range R> requires permutable<iterator_t<R>> constexpr borrowed_subrange_t<R> shift_left(R&& r, range_difference_t<R> n); } template<class ForwardIter> constexpr ForwardIter shift_right(ForwardIter first, ForwardIter last, typename iterator_traits<ForwardIter>::difference_type n); template<class ExecutionPolicy, class ForwardIter> ForwardIter shift_right(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, typename iterator_traits<ForwardIter>::difference_type n); namespace ranges { template<permutable I, sentinel_for<I> S> constexpr subrange<I> shift_right(I first, S last, iter_difference_t<I> n); template<forward_range R> requires permutable<iterator_t<R>> constexpr borrowed_subrange_t<R> shift_right(R&& r, range_difference_t<R> n); } // sorting and related operations // sorting template<class RandomAccessIter> constexpr void sort(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void sort(RandomAccessIter first, RandomAccessIter last, Compare comp); template<class ExecutionPolicy, class RandomAccessIter> void sort(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last); template<class ExecutionPolicy, class RandomAccessIter, class Compare> void sort(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I sort(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> sort(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> void stable_sort(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> void stable_sort(RandomAccessIter first, RandomAccessIter last, Compare comp); template<class ExecutionPolicy, class RandomAccessIter> void stable_sort(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last); template<class ExecutionPolicy, class RandomAccessIter, class Compare> void stable_sort(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> I stable_sort(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> borrowed_iterator_t<R> stable_sort(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> constexpr void partial_sort(RandomAccessIter first, RandomAccessIter middle, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void partial_sort(RandomAccessIter first, RandomAccessIter middle, RandomAccessIter last, Compare comp); template<class ExecutionPolicy, class RandomAccessIter> void partial_sort(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter middle, RandomAccessIter last); template<class ExecutionPolicy, class RandomAccessIter, class Compare> void partial_sort(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter middle, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I partial_sort(I first, I middle, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> partial_sort(R&& r, iterator_t<R> middle, Comp comp = {}, Proj proj = {}); } template<class InputIter, class RandomAccessIter> constexpr RandomAccessIter partial_sort_copy(InputIter first, InputIter last, RandomAccessIter result_first, RandomAccessIter result_last); template<class InputIter, class RandomAccessIter, class Compare> constexpr RandomAccessIter partial_sort_copy(InputIter first, InputIter last, RandomAccessIter result_first, RandomAccessIter result_last, Compare comp); template<class ExecutionPolicy, class ForwardIter, class RandomAccessIter> RandomAccessIter partial_sort_copy(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, RandomAccessIter result_first, RandomAccessIter result_last); template<class ExecutionPolicy, class ForwardIter, class RandomAccessIter, class Compare> RandomAccessIter partial_sort_copy(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, RandomAccessIter result_first, RandomAccessIter result_last, Compare comp); namespace ranges { template<class I, class O> using partial_sort_copy_result = in_out_result<I, O>; template<input_iterator I1, sentinel_for<I1> S1, random_access_iterator I2, sentinel_for<I2> S2, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires indirectly_copyable<I1, I2> && sortable<I2, Comp, Proj2> && indirect_strict_weak_order<Comp, projected<I1, Proj1>, projected<I2, Proj2>> constexpr partial_sort_copy_result<I1, I2> partial_sort_copy(I1 first, S1 last, I2 result_first, S2 result_last, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, random_access_range R2, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires indirectly_copyable<iterator_t<R1>, iterator_t<R2>> && sortable<iterator_t<R2>, Comp, Proj2> && indirect_strict_weak_order<Comp, projected<iterator_t<R1>, Proj1>, projected<iterator_t<R2>, Proj2>> constexpr partial_sort_copy_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>> partial_sort_copy(R1&& r, R2&& result_r, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class ForwardIter> constexpr bool is_sorted(ForwardIter first, ForwardIter last); template<class ForwardIter, class Compare> constexpr bool is_sorted(ForwardIter first, ForwardIter last, Compare comp); template<class ExecutionPolicy, class ForwardIter> bool is_sorted(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class Compare> bool is_sorted(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr bool is_sorted(I first, S last, Comp comp = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr bool is_sorted(R&& r, Comp comp = {}, Proj proj = {}); } template<class ForwardIter> constexpr ForwardIter is_sorted_until(ForwardIter first, ForwardIter last); template<class ForwardIter, class Compare> constexpr ForwardIter is_sorted_until(ForwardIter first, ForwardIter last, Compare comp); template<class ExecutionPolicy, class ForwardIter> ForwardIter is_sorted_until(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class Compare> ForwardIter is_sorted_until(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr I is_sorted_until(I first, S last, Comp comp = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> is_sorted_until(R&& r, Comp comp = {}, Proj proj = {}); } // Nth element template<class RandomAccessIter> constexpr void nth_element(RandomAccessIter first, RandomAccessIter nth, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void nth_element(RandomAccessIter first, RandomAccessIter nth, RandomAccessIter last, Compare comp); template<class ExecutionPolicy, class RandomAccessIter> void nth_element(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter nth, RandomAccessIter last); template<class ExecutionPolicy, class RandomAccessIter, class Compare> void nth_element(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter nth, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I nth_element(I first, I nth, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> nth_element(R&& r, iterator_t<R> nth, Comp comp = {}, Proj proj = {}); } // binary search template<class ForwardIter, class T> constexpr ForwardIter lower_bound(ForwardIter first, ForwardIter last, const T& value); template<class ForwardIter, class T, class Compare> constexpr ForwardIter lower_bound(ForwardIter first, ForwardIter last, const T& value, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<I, Proj>> Comp = ranges::less> constexpr I lower_bound(I first, S last, const T& value, Comp comp = {}, Proj proj = {}); template<forward_range R, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> lower_bound(R&& r, const T& value, Comp comp = {}, Proj proj = {}); } template<class ForwardIter, class T> constexpr ForwardIter upper_bound(ForwardIter first, ForwardIter last, const T& value); template<class ForwardIter, class T, class Compare> constexpr ForwardIter upper_bound(ForwardIter first, ForwardIter last, const T& value, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<I, Proj>> Comp = ranges::less> constexpr I upper_bound(I first, S last, const T& value, Comp comp = {}, Proj proj = {}); template<forward_range R, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> upper_bound(R&& r, const T& value, Comp comp = {}, Proj proj = {}); } template<class ForwardIter, class T> constexpr pair<ForwardIter, ForwardIter> equal_range(ForwardIter first, ForwardIter last, const T& value); template<class ForwardIter, class T, class Compare> constexpr pair<ForwardIter, ForwardIter> equal_range(ForwardIter first, ForwardIter last, const T& value, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<I, Proj>> Comp = ranges::less> constexpr subrange<I> equal_range(I first, S last, const T& value, Comp comp = {}, Proj proj = {}); template<forward_range R, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_subrange_t<R> equal_range(R&& r, const T& value, Comp comp = {}, Proj proj = {}); } template<class ForwardIter, class T> constexpr bool binary_search(ForwardIter first, ForwardIter last, const T& value); template<class ForwardIter, class T, class Compare> constexpr bool binary_search(ForwardIter first, ForwardIter last, const T& value, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<I, Proj>> Comp = ranges::less> constexpr bool binary_search(I first, S last, const T& value, Comp comp = {}, Proj proj = {}); template<forward_range R, class T, class Proj = identity, indirect_strict_weak_order<const T*, projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr bool binary_search(R&& r, const T& value, Comp comp = {}, Proj proj = {}); } // partitions template<class InputIter, class Pred> constexpr bool is_partitioned(InputIter first, InputIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> bool is_partitioned(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr bool is_partitioned(I first, S last, Pred pred, Proj proj = {}); template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr bool is_partitioned(R&& r, Pred pred, Proj proj = {}); } template<class ForwardIter, class Pred> constexpr ForwardIter partition(ForwardIter first, ForwardIter last, Pred pred); template<class ExecutionPolicy, class ForwardIter, class Pred> ForwardIter partition(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<permutable I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr subrange<I> partition(I first, S last, Pred pred, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires permutable<iterator_t<R>> constexpr borrowed_subrange_t<R> partition(R&& r, Pred pred, Proj proj = {}); } template<class BidirectionalIter, class Pred> BidirectionalIter stable_partition(BidirectionalIter first, BidirectionalIter last, Pred pred); template<class ExecutionPolicy, class BidirectionalIter, class Pred> BidirectionalIter stable_partition(ExecutionPolicy&& exec, BidirectionalIter first, BidirectionalIter last, Pred pred); namespace ranges { template<bidirectional_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> requires permutable<I> subrange<I> stable_partition(I first, S last, Pred pred, Proj proj = {}); template<bidirectional_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires permutable<iterator_t<R>> borrowed_subrange_t<R> stable_partition(R&& r, Pred pred, Proj proj = {}); } template<class InputIter, class OutputIter1, class OutputIter2, class Pred> constexpr pair<OutputIter1, OutputIter2> partition_copy(InputIter first, InputIter last, OutputIter1 out_true, OutputIter2 out_false, Pred pred); template<class ExecutionPolicy, class ForwardIter, class ForwardIter1, class ForwardIter2, class Pred> pair<ForwardIter1, ForwardIter2> partition_copy(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, ForwardIter1 out_true, ForwardIter2 out_false, Pred pred); namespace ranges { template<class I, class O1, class O2> using partition_copy_result = in_out_out_result<I, O1, O2>; template<input_iterator I, sentinel_for<I> S, weakly_incrementable O1, weakly_incrementable O2, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> requires indirectly_copyable<I, O1> && indirectly_copyable<I, O2> constexpr partition_copy_result<I, O1, O2> partition_copy(I first, S last, O1 out_true, O2 out_false, Pred pred, Proj proj = {}); template<input_range R, weakly_incrementable O1, weakly_incrementable O2, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> requires indirectly_copyable<iterator_t<R>, O1> && indirectly_copyable<iterator_t<R>, O2> constexpr partition_copy_result<borrowed_iterator_t<R>, O1, O2> partition_copy(R&& r, O1 out_true, O2 out_false, Pred pred, Proj proj = {}); } template<class ForwardIter, class Pred> constexpr ForwardIter partition_point(ForwardIter first, ForwardIter last, Pred pred); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred> constexpr I partition_point(I first, S last, Pred pred, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred> constexpr borrowed_iterator_t<R> partition_point(R&& r, Pred pred, Proj proj = {}); } // merge template<class InputIter1, class InputIter2, class OutputIter> constexpr OutputIter merge(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result); template<class InputIter1, class InputIter2, class OutputIter, class Compare> constexpr OutputIter merge(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter> ForwardIter merge(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter, class Compare> ForwardIter merge(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result, Compare comp); namespace ranges { template<class I1, class I2, class O> using merge_result = in_in_out_result<I1, I2, O>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr merge_result<I1, I2, O> merge(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr merge_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O> merge(R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class BidirectionalIter> void inplace_merge(BidirectionalIter first, BidirectionalIter middle, BidirectionalIter last); template<class BidirectionalIter, class Compare> void inplace_merge(BidirectionalIter first, BidirectionalIter middle, BidirectionalIter last, Compare comp); template<class ExecutionPolicy, class BidirectionalIter> void inplace_merge(ExecutionPolicy&& exec, BidirectionalIter first, BidirectionalIter middle, BidirectionalIter last); template<class ExecutionPolicy, class BidirectionalIter, class Compare> void inplace_merge(ExecutionPolicy&& exec, BidirectionalIter first, BidirectionalIter middle, BidirectionalIter last, Compare comp); namespace ranges { template<bidirectional_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> I inplace_merge(I first, I middle, S last, Comp comp = {}, Proj proj = {}); template<bidirectional_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> borrowed_iterator_t<R> inplace_merge(R&& r, iterator_t<R> middle, Comp comp = {}, Proj proj = {}); } // set operations template<class InputIter1, class InputIter2> constexpr bool includes(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2); template<class InputIter1, class InputIter2, class Compare> constexpr bool includes(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> bool includes(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class Compare> bool includes(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, Compare comp); namespace ranges { template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, class Proj1 = identity, class Proj2 = identity, indirect_strict_weak_order<projected<I1, Proj1>, projected<I2, Proj2>> Comp = ranges::less> constexpr bool includes(I1 first1, S1 last1, I2 first2, S2 last2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, class Proj1 = identity, class Proj2 = identity, indirect_strict_weak_order<projected<iterator_t<R1>, Proj1>, projected<iterator_t<R2>, Proj2>> Comp = ranges::less> constexpr bool includes(R1&& r1, R2&& r2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class InputIter1, class InputIter2, class OutputIter> constexpr OutputIter set_union(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result); template<class InputIter1, class InputIter2, class OutputIter, class Compare> constexpr OutputIter set_union(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter> ForwardIter set_union(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter, class Compare> ForwardIter set_union(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result, Compare comp); namespace ranges { template<class I1, class I2, class O> using set_union_result = in_in_out_result<I1, I2, O>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_union_result<I1, I2, O> set_union(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_union_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O> set_union(R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class InputIter1, class InputIter2, class OutputIter> constexpr OutputIter set_intersection(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result); template<class InputIter1, class InputIter2, class OutputIter, class Compare> constexpr OutputIter set_intersection(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter> ForwardIter set_intersection(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter, class Compare> ForwardIter set_intersection(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result, Compare comp); namespace ranges { template<class I1, class I2, class O> using set_intersection_result = in_in_out_result<I1, I2, O>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_intersection_result<I1, I2, O> set_intersection(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_intersection_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O> set_intersection(R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class InputIter1, class InputIter2, class OutputIter> constexpr OutputIter set_difference(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result); template<class InputIter1, class InputIter2, class OutputIter, class Compare> constexpr OutputIter set_difference(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter> ForwardIter set_difference(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter, class Compare> ForwardIter set_difference(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result, Compare comp); namespace ranges { template<class I, class O> using set_difference_result = in_out_result<I, O>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_difference_result<I1, O> set_difference(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_difference_result<borrowed_iterator_t<R1>, O> set_difference(R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } template<class InputIter1, class InputIter2, class OutputIter> constexpr OutputIter set_symmetric_difference(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result); template<class InputIter1, class InputIter2, class OutputIter, class Compare> constexpr OutputIter set_symmetric_difference(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, OutputIter result, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter> ForwardIter set_symmetric_difference(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class ForwardIter, class Compare> ForwardIter set_symmetric_difference(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, ForwardIter result, Compare comp); namespace ranges { template<class I1, class I2, class O> using set_symmetric_difference_result = in_in_out_result<I1, I2, O>; template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_symmetric_difference_result<I1, I2, O> set_symmetric_difference(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity, class Proj2 = identity> requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_symmetric_difference_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O> set_symmetric_difference(R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // heap operations template<class RandomAccessIter> constexpr void push_heap(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void push_heap(RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I push_heap(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> push_heap(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> constexpr void pop_heap(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void pop_heap(RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I pop_heap(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> pop_heap(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> constexpr void make_heap(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void make_heap(RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I make_heap(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> make_heap(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> constexpr void sort_heap(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr void sort_heap(RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr I sort_heap(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr borrowed_iterator_t<R> sort_heap(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> constexpr bool is_heap(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr bool is_heap(RandomAccessIter first, RandomAccessIter last, Compare comp); template<class ExecutionPolicy, class RandomAccessIter> bool is_heap(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last); template<class ExecutionPolicy, class RandomAccessIter, class Compare> bool is_heap(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr bool is_heap(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr bool is_heap(R&& r, Comp comp = {}, Proj proj = {}); } template<class RandomAccessIter> constexpr RandomAccessIter is_heap_until(RandomAccessIter first, RandomAccessIter last); template<class RandomAccessIter, class Compare> constexpr RandomAccessIter is_heap_until(RandomAccessIter first, RandomAccessIter last, Compare comp); template<class ExecutionPolicy, class RandomAccessIter> RandomAccessIter is_heap_until(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last); template<class ExecutionPolicy, class RandomAccessIter, class Compare> RandomAccessIter is_heap_until(ExecutionPolicy&& exec, RandomAccessIter first, RandomAccessIter last, Compare comp); namespace ranges { template<random_access_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr I is_heap_until(I first, S last, Comp comp = {}, Proj proj = {}); template<random_access_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> is_heap_until(R&& r, Comp comp = {}, Proj proj = {}); } // minimum and maximum template<class T> constexpr const T& min(const T& a, const T& b); template<class T, class Compare> constexpr const T& min(const T& a, const T& b, Compare comp); template<class T> constexpr T min(initializer_list<T> t); template<class T, class Compare> constexpr T min(initializer_list<T> t, Compare comp); namespace ranges { template<class T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr const T& min(const T& a, const T& b, Comp comp = {}, Proj proj = {}); template<copyable T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr T min(initializer_list<T> r, Comp comp = {}, Proj proj = {}); template<input_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> requires indirectly_copyable_storable<iterator_t<R>, range_value_t<R>*> constexpr range_value_t<R> min(R&& r, Comp comp = {}, Proj proj = {}); } template<class T> constexpr const T& max(const T& a, const T& b); template<class T, class Compare> constexpr const T& max(const T& a, const T& b, Compare comp); template<class T> constexpr T max(initializer_list<T> t); template<class T, class Compare> constexpr T max(initializer_list<T> t, Compare comp); namespace ranges { template<class T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr const T& max(const T& a, const T& b, Comp comp = {}, Proj proj = {}); template<copyable T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr T max(initializer_list<T> r, Comp comp = {}, Proj proj = {}); template<input_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> requires indirectly_copyable_storable<iterator_t<R>, range_value_t<R>*> constexpr range_value_t<R> max(R&& r, Comp comp = {}, Proj proj = {}); } template<class T> constexpr pair<const T&, const T&> minmax(const T& a, const T& b); template<class T, class Compare> constexpr pair<const T&, const T&> minmax(const T& a, const T& b, Compare comp); template<class T> constexpr pair<T, T> minmax(initializer_list<T> t); template<class T, class Compare> constexpr pair<T, T> minmax(initializer_list<T> t, Compare comp); namespace ranges { template<class T> using minmax_result = min_max_result<T>; template<class T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr minmax_result<const T&> minmax(const T& a, const T& b, Comp comp = {}, Proj proj = {}); template<copyable T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr minmax_result<T> minmax(initializer_list<T> r, Comp comp = {}, Proj proj = {}); template<input_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> requires indirectly_copyable_storable<iterator_t<R>, range_value_t<R>*> constexpr minmax_result<range_value_t<R>> minmax(R&& r, Comp comp = {}, Proj proj = {}); } template<class ForwardIter> constexpr ForwardIter min_element(ForwardIter first, ForwardIter last); template<class ForwardIter, class Compare> constexpr ForwardIter min_element(ForwardIter first, ForwardIter last, Compare comp); template<class ExecutionPolicy, class ForwardIter> ForwardIter min_element(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class Compare> ForwardIter min_element(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr I min_element(I first, S last, Comp comp = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> min_element(R&& r, Comp comp = {}, Proj proj = {}); } template<class ForwardIter> constexpr ForwardIter max_element(ForwardIter first, ForwardIter last); template<class ForwardIter, class Compare> constexpr ForwardIter max_element(ForwardIter first, ForwardIter last, Compare comp); template<class ExecutionPolicy, class ForwardIter> ForwardIter max_element(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class Compare> ForwardIter max_element(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Compare comp); namespace ranges { template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr I max_element(I first, S last, Comp comp = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> max_element(R&& r, Comp comp = {}, Proj proj = {}); } template<class ForwardIter> constexpr pair<ForwardIter, ForwardIter> minmax_element(ForwardIter first, ForwardIter last); template<class ForwardIter, class Compare> constexpr pair<ForwardIter, ForwardIter> minmax_element(ForwardIter first, ForwardIter last, Compare comp); template<class ExecutionPolicy, class ForwardIter> pair<ForwardIter, ForwardIter> minmax_element(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last); template<class ExecutionPolicy, class ForwardIter, class Compare> pair<ForwardIter, ForwardIter> minmax_element(ExecutionPolicy&& exec, ForwardIter first, ForwardIter last, Compare comp); namespace ranges { template<class I> using minmax_element_result = min_max_result<I>; template<forward_iterator I, sentinel_for<I> S, class Proj = identity, indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less> constexpr minmax_element_result<I> minmax_element(I first, S last, Comp comp = {}, Proj proj = {}); template<forward_range R, class Proj = identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr minmax_element_result<borrowed_iterator_t<R>> minmax_element(R&& r, Comp comp = {}, Proj proj = {}); } // bounded value template<class T> constexpr const T& clamp(const T& v, const T& lo, const T& hi); template<class T, class Compare> constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp); namespace ranges { template<class T, class Proj = identity, indirect_strict_weak_order<projected<const T*, Proj>> Comp = ranges::less> constexpr const T& clamp(const T& v, const T& lo, const T& hi, Comp comp = {}, Proj proj = {}); } // lexicographical comparison template<class InputIter1, class InputIter2> constexpr bool lexicographical_compare(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2); template<class InputIter1, class InputIter2, class Compare> constexpr bool lexicographical_compare(InputIter1 first1, InputIter1 last1, InputIter2 first2, InputIter2 last2, Compare comp); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2> bool lexicographical_compare(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2); template<class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class Compare> bool lexicographical_compare(ExecutionPolicy&& exec, ForwardIter1 first1, ForwardIter1 last1, ForwardIter2 first2, ForwardIter2 last2, Compare comp); namespace ranges { template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2, class Proj1 = identity, class Proj2 = identity, indirect_strict_weak_order<projected<I1, Proj1>, projected<I2, Proj2>> Comp = ranges::less> constexpr bool lexicographical_compare(I1 first1, S1 last1, I2 first2, S2 last2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); template<input_range R1, input_range R2, class Proj1 = identity, class Proj2 = identity, indirect_strict_weak_order<projected<iterator_t<R1>, Proj1>, projected<iterator_t<R2>, Proj2>> Comp = ranges::less> constexpr bool lexicographical_compare(R1&& r1, R2&& r2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}); } // three-way comparison algorithms template<class InputIter1, class InputIter2, class Cmp> constexpr auto lexicographical_compare_three_way(InputIter1 b1, InputIter1 e1, InputIter2 b2, InputIter2 e2, Cmp comp) -> decltype(comp(*b1, *b2)); template<class InputIter1, class InputIter2> constexpr auto lexicographical_compare_three_way(InputIter1 b1, InputIter1 e1, InputIter2 b2, InputIter2 e2); // permutations template<class BidirectionalIter> constexpr bool next_permutation(BidirectionalIter first, BidirectionalIter last); template<class BidirectionalIter, class Compare> constexpr bool next_permutation(BidirectionalIter first, BidirectionalIter last, Compare comp); namespace ranges { template<class I> using next_permutation_result = in_found_result<I>; template<bidirectional_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr next_permutation_result<I> next_permutation(I first, S last, Comp comp = {}, Proj proj = {}); template<bidirectional_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr next_permutation_result<borrowed_iterator_t<R>> next_permutation(R&& r, Comp comp = {}, Proj proj = {}); } template<class BidirectionalIter> constexpr bool prev_permutation(BidirectionalIter first, BidirectionalIter last); template<class BidirectionalIter, class Compare> constexpr bool prev_permutation(BidirectionalIter first, BidirectionalIter last, Compare comp); namespace ranges { template<class I> using prev_permutation_result = in_found_result<I>; template<bidirectional_iterator I, sentinel_for<I> S, class Comp = ranges::less, class Proj = identity> requires sortable<I, Comp, Proj> constexpr prev_permutation_result<I> prev_permutation(I first, S last, Comp comp = {}, Proj proj = {}); template<bidirectional_range R, class Comp = ranges::less, class Proj = identity> requires sortable<iterator_t<R>, Comp, Proj> constexpr prev_permutation_result<borrowed_iterator_t<R>> prev_permutation(R&& r, Comp comp = {}, Proj proj = {}); } } ``` #### Class template `[std::ranges::in\_fun\_result](../algorithm/ranges/return_types/in_fun_result "cpp/algorithm/ranges/return types/in fun result")` ``` namespace std::ranges { template<class I, class F> struct in_fun_result { [[no_unique_address]] I in; [[no_unique_address]] F fun; template<class I2, class F2> requires convertible_to<const I&, I2> && convertible_to<const F&, F2> constexpr operator in_fun_result<I2, F2>() const & { return {in, fun}; } template<class I2, class F2> requires convertible_to<I, I2> && convertible_to<F, F2> constexpr operator in_fun_result<I2, F2>() && { return {std::move(in), std::move(fun)}; } }; } ``` #### Class template `[std::ranges::in\_in\_result](../algorithm/ranges/return_types/in_in_result "cpp/algorithm/ranges/return types/in in result")` ``` namespace std::ranges { template<class I1, class I2> struct in_in_result { [[no_unique_address]] I1 in1; [[no_unique_address]] I2 in2; template<class II1, class II2> requires convertible_to<const I1&, II1> && convertible_to<const I2&, II2> constexpr operator in_in_result<II1, II2>() const & { return {in1, in2}; } template<class II1, class II2> requires convertible_to<I1, II1> && convertible_to<I2, II2> constexpr operator in_in_result<II1, II2>() && { return {std::move(in1), std::move(in2)}; } }; } ``` #### Class template `[std::ranges::in\_out\_result](../algorithm/ranges/return_types/in_out_result "cpp/algorithm/ranges/return types/in out result")` ``` namespace std::ranges { template<class I, class O> struct in_out_result { [[no_unique_address]] I in; [[no_unique_address]] O out; template<class I2, class O2> requires convertible_to<const I&, I2> && convertible_to<const O&, O2> constexpr operator in_out_result<I2, O2>() const & { return {in, out}; } template<class I2, class O2> requires convertible_to<I, I2> && convertible_to<O, O2> constexpr operator in_out_result<I2, O2>() && { return {std::move(in), std::move(out)}; } }; } ``` #### Class template `[std::ranges::in\_in\_out\_result](../algorithm/ranges/return_types/in_in_out_result "cpp/algorithm/ranges/return types/in in out result")` ``` namespace std::ranges { template<class I1, class I2, class O> struct in_in_out_result { [[no_unique_address]] I1 in1; [[no_unique_address]] I2 in2; [[no_unique_address]] O out; template<class II1, class II2, class OO> requires convertible_to<const I1&, II1> && convertible_to<const I2&, II2> && convertible_to<const O&, OO> constexpr operator in_in_out_result<II1, II2, OO>() const & { return {in1, in2, out}; } template<class II1, class II2, class OO> requires convertible_to<I1, II1> && convertible_to<I2, II2> && convertible_to<O, OO> constexpr operator in_in_out_result<II1, II2, OO>() && { return {std::move(in1), std::move(in2), std::move(out)}; } }; } ``` #### Class template `[std::ranges::in\_out\_out\_result](../algorithm/ranges/return_types/in_out_out_result "cpp/algorithm/ranges/return types/in out out result")` ``` namespace std::ranges { template<class I, class O1, class O2> struct in_out_out_result { [[no_unique_address]] I in; [[no_unique_address]] O1 out1; [[no_unique_address]] O2 out2; template<class II, class OO1, class OO2> requires convertible_to<const I&, II> && convertible_to<const O1&, OO1> && convertible_to<const O2&, OO2> constexpr operator in_out_out_result<II, OO1, OO2>() const & { return {in, out1, out2}; } template<class II, class OO1, class OO2> requires convertible_to<I, II> && convertible_to<O1, OO1> && convertible_to<O2, OO2> constexpr operator in_out_out_result<II, OO1, OO2>() && { return {std::move(in), std::move(out1), std::move(out2)}; } }; } ``` #### Class template `[std::ranges::min\_max\_result](../algorithm/ranges/return_types/min_max_result "cpp/algorithm/ranges/return types/min max result")` ``` namespace std::ranges { template<class T> struct min_max_result { [[no_unique_address]] T min; [[no_unique_address]] T max; template<class T2> requires convertible_to<const T&, T2> constexpr operator min_max_result<T2>() const & { return {min, max}; } template<class T2> requires convertible_to<T, T2> constexpr operator min_max_result<T2>() && { return {std::move(min), std::move(max)}; } }; } ``` #### Class template `[std::ranges::in\_found\_result](../algorithm/ranges/return_types/in_found_result "cpp/algorithm/ranges/return types/in found result")` ``` namespace std::ranges { template<class I> struct in_found_result { [[no_unique_address]] I in; bool found; template<class I2> requires convertible_to<const I&, I2> constexpr operator in_found_result<I2>() const & { return {in, found}; } template<class I2> requires convertible_to<I, I2> constexpr operator in_found_result<I2>() && { return {std::move(in), found}; } }; } ``` #### Class template `std::ranges::in_value_result` ``` namespace std::ranges { template<class I, class T> struct in_value_result { [[no_unique_address]] I in; [[no_unique_address]] T value; template<class I2, class T2> requires convertible_to<const I&, I2> && convertible_to<const T&, T2> constexpr operator in_value_result<I2, T2>() const & { return {in, value}; } template<class I2, class T2> requires convertible_to<I, I2> && convertible_to<T, T2> constexpr operator in_value_result<I2, T2>() && { return {std::move(in), std::move(value)}; } }; } ``` #### Class template `std::ranges::out_value_result` ``` namespace std::ranges { template<class O, class T> struct out_value_result { [[no_unique_address]] O out; [[no_unique_address]] T value; template<class O2, class T2> requires convertible_to<const O&, O2> && convertible_to<const T&, T2> constexpr operator out_value_result<O2, T2>() const & { return {out, value}; } template<class O2, class T2> requires convertible_to<O, O2> && convertible_to<T, T2> constexpr operator out_value_result<O2, T2>() && { return {std::move(out), std::move(value)}; } }; } ```
programming_docs
cpp Standard library header <string_view> (C++17) Standard library header <string\_view> (C++17) ============================================== This header is part of the [strings](../string "cpp/string") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [basic\_string\_view](../string/basic_string_view "cpp/string/basic string view") (C++17) | read-only string view (class template) | | `[std::string\_view](../string/basic_string_view "cpp/string/basic string view")` (C++17) | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<char>` | | `[std::u8string\_view](../string/basic_string_view "cpp/string/basic string view")` (C++20) | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<char8_t>` | | `[std::u16string\_view](../string/basic_string_view "cpp/string/basic string view")` (C++17) | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<char16\_t>` | | `[std::u32string\_view](../string/basic_string_view "cpp/string/basic string view")` (C++17) | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<char32\_t>` | | `[std::wstring\_view](../string/basic_string_view "cpp/string/basic string view")` (C++17) | `[std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)<wchar\_t>` | | [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>](../string/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) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Functions | | [operator==operator!=operator<operator>operator<=operator>=operator<=>](../string/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) | | [operator<<](../string/basic_string_view/operator_ltlt "cpp/string/basic string view/operator ltlt") (C++17) | performs stream output on string views (function template) | | [swap](../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | | Literals | | Defined in inline namespace `std::literals::string_view_literals` | | [operator""sv](../string/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) | ### Synopsis ``` #include <compare> namespace std { // class template basic_string_view template<class CharT, class Traits = char_traits<CharT>> class basic_string_view; template<class CharT, class Traits> inline constexpr bool ranges::enable_view<basic_string_view<CharT, Traits>> = true; template<class CharT, class Traits> inline constexpr bool ranges::enable_borrowed_range<basic_string_view<CharT, Traits>> = true; // non-member comparison functions template<class CharT, class Traits> constexpr bool operator==(basic_string_view<CharT, Traits> x, basic_string_view<CharT, Traits> y) noexcept; template<class CharT, class Traits> constexpr /* see description */ operator<=>(basic_string_view<CharT, Traits> x, basic_string_view<CharT, Traits> y) noexcept; // sufficient additional overloads of comparison functions // inserters and extractors template<class CharT, class Traits> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& os, basic_string_view<CharT, Traits> str); // basic_string_view typedef names using string_view = basic_string_view<char>; using u8string_view = basic_string_view<char8_t>; using u16string_view = basic_string_view<char16_t>; using u32string_view = basic_string_view<char32_t>; using wstring_view = basic_string_view<wchar_t>; // hash support template<class T> struct hash; template<> struct hash<string_view>; template<> struct hash<u8string_view>; template<> struct hash<u16string_view>; template<> struct hash<u32string_view>; template<> struct hash<wstring_view>; inline namespace literals { inline namespace string_view_literals { // suffix for basic_string_view literals constexpr string_view operator""sv(const char* str, size_t len) noexcept; constexpr u8string_view operator""sv(const char8_t* str, size_t len) noexcept; constexpr u16string_view operator""sv(const char16_t* str, size_t len) noexcept; constexpr u32string_view operator""sv(const char32_t* str, size_t len) noexcept; constexpr wstring_view operator""sv(const wchar_t* str, size_t len) noexcept; } } } ``` #### Class template `[std::basic\_string\_view](../string/basic_string_view "cpp/string/basic string view")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_string_view { public: // types using Traits_type = Traits; using value_type = CharT; using pointer = value_type*; using const_pointer = const value_type*; using reference = value_type&; using const_reference = const value_type&; using const_iterator = /* implementation-defined */ using iterator = const_iterator; using const_reverse_iterator = reverse_iterator<const_iterator>; using reverse_iterator = const_reverse_iterator; using size_type = size_t; using difference_type = ptrdiff_t; static constexpr size_type npos = size_type(-1); // construction and assignment constexpr basic_string_view() noexcept; constexpr basic_string_view(const basic_string_view&) noexcept = default; constexpr basic_string_view& operator=(const basic_string_view&) noexcept = default; constexpr basic_string_view(const CharT* str); constexpr basic_string_view(nullptr_t) = delete; constexpr basic_string_view(const CharT* str, size_type len); template<class It, class End> constexpr basic_string_view(It begin, End end); template<class R> constexpr explicit basic_string_view(R&& r); // iterator support constexpr const_iterator begin() const noexcept; constexpr const_iterator end() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_reverse_iterator rbegin() const noexcept; constexpr const_reverse_iterator rend() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept; constexpr const_reverse_iterator crend() const noexcept; // capacity constexpr size_type size() const noexcept; constexpr size_type length() const noexcept; constexpr size_type max_size() const noexcept; [[nodiscard]] constexpr bool empty() const noexcept; // element access constexpr const_reference operator[](size_type pos) const; constexpr const_reference at(size_type pos) const; constexpr const_reference front() const; constexpr const_reference back() const; constexpr const_pointer data() const noexcept; // modifiers constexpr void remove_prefix(size_type n); constexpr void remove_suffix(size_type n); constexpr void swap(basic_string_view& s) noexcept; // string operations constexpr size_type copy(CharT* s, size_type n, size_type pos = 0) const; constexpr basic_string_view substr(size_type pos = 0, size_type n = npos) const; constexpr int compare(basic_string_view s) const noexcept; constexpr int compare(size_type pos1, size_type n1, basic_string_view s) const; constexpr int compare(size_type pos1, size_type n1, basic_string_view s, size_type pos2, size_type n2) const; constexpr int compare(const CharT* s) const; constexpr int compare(size_type pos1, size_type n1, const CharT* s) const; constexpr int compare(size_type pos1, size_type n1, const CharT* s, size_type n2) const; constexpr bool starts_with(basic_string_view x) const noexcept; constexpr bool starts_with(CharT x) const noexcept; constexpr bool starts_with(const CharT* x) const; constexpr bool ends_with(basic_string_view x) const noexcept; constexpr bool ends_with(CharT x) const noexcept; constexpr bool ends_with(const CharT* x) const; constexpr bool contains(basic_string_view x) const noexcept; constexpr bool contains(CharT x) const noexcept; constexpr bool contains(const CharT* x) const; // searching constexpr size_type find(basic_string_view s, size_type pos = 0) const noexcept; constexpr size_type find(CharT c, size_type pos = 0) const noexcept; constexpr size_type find(const CharT* s, size_type pos, size_type n) const; constexpr size_type find(const CharT* s, size_type pos = 0) const; constexpr size_type rfind(basic_string_view s, size_type pos = npos) const noexcept; constexpr size_type rfind(CharT c, size_type pos = npos) const noexcept; constexpr size_type rfind(const CharT* s, size_type pos, size_type n) const; constexpr size_type rfind(const CharT* s, size_type pos = npos) const; constexpr size_type find_first_of(basic_string_view s, size_type pos = 0) const noexcept; constexpr size_type find_first_of(CharT c, size_type pos = 0) const noexcept; constexpr size_type find_first_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_first_of(const CharT* s, size_type pos = 0) const; constexpr size_type find_last_of(basic_string_view s, size_type pos = npos) const noexcept; constexpr size_type find_last_of(CharT c, size_type pos = npos) const noexcept; constexpr size_type find_last_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_last_of(const CharT* s, size_type pos = npos) const; constexpr size_type find_first_not_of(basic_string_view s, size_type pos = 0) const noexcept; constexpr size_type find_first_not_of(CharT c, size_type pos = 0) const noexcept; constexpr size_type find_first_not_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_first_not_of(const CharT* s, size_type pos = 0) const; constexpr size_type find_last_not_of(basic_string_view s, size_type pos = npos) const noexcept; constexpr size_type find_last_not_of(CharT c, size_type pos = npos) const noexcept; constexpr size_type find_last_not_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_last_not_of(const CharT* s, size_type pos = npos) const; private: const_pointer data_; // exposition only size_type size_; // exposition only }; // deduction guides template<class It, class End> basic_string_view(It, End) -> basic_string_view<iter_value_t<It>>; template<class R> basic_string_view(R&&) -> basic_string_view<ranges::range_value_t<R>>; } ``` cpp Standard library header <ciso646> (until C++20), <iso646.h> Standard library header <ciso646> (until C++20), <iso646.h> =========================================================== This header was originally in the C standard library as `<iso646.h>`. Compatibility header, in C defines [alternative operator representations](../language/operator_alternative "cpp/language/operator alternative") which are keywords in C++. This means that in a conforming implementation, including this header has no effect. ### Notes In old or nonconforming compilers, using the [alternative operator representations](../language/operator_alternative "cpp/language/operator alternative") may still require including this header. Prior to C++20, including `<ciso646>` was sometimes used as a technique for obtaining definitions of implementation-specific library version macros without causing other effects. As of C++20, the header [`<version>`](version "cpp/header/version") was added for this purpose. `<ciso646>` is removed in C++20. Corresponding `<iso646.h>` is still available in C++20. ``` #include <ciso646> #ifdef _LIBCPP_VERSION #error Using LLVM libc++ #elif __GLIBCXX__ // Note: only version 6.1 or newer define this in ciso646 #error Using GNU libstdc++ #elif _CPPLIB_VER // Note: used by Visual Studio #error Using Microsoft STL #else #error Using an unknown standard library #endif ``` Possible output: ``` main.cpp:7:2: error: Using Microsoft STL #error Using Microsoft STL ^ 1 error generated. ``` cpp Standard library header <variant> (C++17) Standard library header <variant> (C++17) ========================================= This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [variant](../utility/variant "cpp/utility/variant") (C++17) | a type-safe discriminated union (class template) | | [monostate](../utility/variant/monostate "cpp/utility/variant/monostate") (C++17) | placeholder type for use as the first alternative in a variant of non-default-constructible types (class) | | [bad\_variant\_access](../utility/variant/bad_variant_access "cpp/utility/variant/bad variant access") (C++17) | exception thrown on invalid accesses to the value of a variant (class) | | [variant\_sizevariant\_size\_v](../utility/variant/variant_size "cpp/utility/variant/variant size") (C++17) | obtains the size of the variant's list of alternatives at compile time (class template) (variable template) | | [variant\_alternativevariant\_alternative\_t](../utility/variant/variant_alternative "cpp/utility/variant/variant alternative") (C++17) | obtains the type of the alternative specified by its index, at compile time (class template) (alias template) | | [std::hash<std::variant>](../utility/variant/hash "cpp/utility/variant/hash") (C++17) | specializes the `[std::hash](../utility/hash "cpp/utility/hash")` algorithm (class template specialization) | | Constants | | [variant\_npos](../utility/variant/variant_npos "cpp/utility/variant/variant npos") (C++17) | index of the variant in the invalid state (constant) | | Functions | | [visit](../utility/variant/visit "cpp/utility/variant/visit") (C++17) | calls the provided functor with the arguments held by one or more variants (function template) | | [holds\_alternative](../utility/variant/holds_alternative "cpp/utility/variant/holds alternative") (C++17) | checks if a variant currently holds a given type (function template) | | [std::get(std::variant)](../utility/variant/get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [get\_if](../utility/variant/get_if "cpp/utility/variant/get if") (C++17) | obtains a pointer to the value of a pointed-to variant given the index or the type (if unique), returns null on error (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../utility/variant/operator_cmp "cpp/utility/variant/operator cmp") (C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20) | compares `variant` objects as their contained values (function template) | | [std::swap(std::variant)](../utility/variant/swap2 "cpp/utility/variant/swap2") (C++17) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` #include <compare> namespace std { // class template variant template<class... Types> class variant; // variant helper classes template<class T> struct variant_size; // not defined template<class T> struct variant_size<const T>; template<class T> inline constexpr size_t variant_size_v = variant_size<T>::value; template<class... Types> struct variant_size<variant<Types...>>; template<size_t I, class T> struct variant_alternative; // not defined template<size_t I, class T> struct variant_alternative<I, const T>; template<size_t I, class T> using variant_alternative_t = typename variant_alternative<I, T>::type; template<size_t I, class... Types> struct variant_alternative<I, variant<Types...>>; inline constexpr size_t variant_npos = -1; // value access template<class T, class... Types> constexpr bool holds_alternative(const variant<Types...>&) noexcept; template<size_t I, class... Types> constexpr variant_alternative_t<I, variant<Types...>>& get(variant<Types...>&); template<size_t I, class... Types> constexpr variant_alternative_t<I, variant<Types...>>&& get(variant<Types...>&&); template<size_t I, class... Types> constexpr const variant_alternative_t<I, variant<Types...>>& get(const variant<Types...>&); template<size_t I, class... Types> constexpr const variant_alternative_t<I, variant<Types...>>&& get(const variant<Types...>&&); template<class T, class... Types> constexpr T& get(variant<Types...>&); template<class T, class... Types> constexpr T&& get(variant<Types...>&&); template<class T, class... Types> constexpr const T& get(const variant<Types...>&); template<class T, class... Types> constexpr const T&& get(const variant<Types...>&&); template<size_t I, class... Types> constexpr add_pointer_t<variant_alternative_t<I, variant<Types...>>> get_if(variant<Types...>*) noexcept; template<size_t I, class... Types> constexpr add_pointer_t<const variant_alternative_t<I, variant<Types...>>> get_if(const variant<Types...>*) noexcept; template<class T, class... Types> constexpr add_pointer_t<T> get_if(variant<Types...>*) noexcept; template<class T, class... Types> constexpr add_pointer_t<const T> get_if(const variant<Types...>*) noexcept; // relational operators template<class... Types> constexpr bool operator==(const variant<Types...>&, const variant<Types...>&); template<class... Types> constexpr bool operator!=(const variant<Types...>&, const variant<Types...>&); template<class... Types> constexpr bool operator<(const variant<Types...>&, const variant<Types...>&); template<class... Types> constexpr bool operator>(const variant<Types...>&, const variant<Types...>&); template<class... Types> constexpr bool operator<=(const variant<Types...>&, const variant<Types...>&); template<class... Types> constexpr bool operator>=(const variant<Types...>&, const variant<Types...>&); template<class... Types> requires (three_way_comparable<Types> && ...) constexpr common_comparison_category_t<compare_three_way_result_t<Types>...> operator<=>(const variant<Types...>&, const variant<Types...>&); // visitation template<class Visitor, class... Variants> constexpr /* see description */ visit(Visitor&&, Variants&&...); template<class R, class Visitor, class... Variants> constexpr R visit(Visitor&&, Variants&&...); // class monostate struct monostate; // monostate relational operators constexpr bool operator==(monostate, monostate) noexcept; constexpr strong_ordering operator<=>(monostate, monostate) noexcept; // specialized algorithms template<class... Types> constexpr void swap(variant<Types...>&, variant<Types...>&) noexcept(/* see description */); // class bad_variant_access class bad_variant_access; // hash support template<class T> struct hash; template<class... Types> struct hash<variant<Types...>>; template<> struct hash<monostate>; } // deprecated namespace std { template<class T> struct variant_size<volatile T>; template<class T> struct variant_size<const volatile T>; template<size_t I, class T> struct variant_alternative<I, volatile T>; template<size_t I, class T> struct variant_alternative<I, const volatile T>; } ``` #### Class template `[std::variant](../utility/variant "cpp/utility/variant")` ``` namespace std { template<class... Types> class variant { public: // constructors constexpr variant() noexcept(/* see description */); constexpr variant(const variant&); constexpr variant(variant&&) noexcept(/* see description */); template<class T> constexpr variant(T&&) noexcept(/* see description */); template<class T, class... Args> constexpr explicit variant(in_place_type_t<T>, Args&&...); template<class T, class U, class... Args> constexpr explicit variant(in_place_type_t<T>, initializer_list<U>, Args&&...); template<size_t I, class... Args> constexpr explicit variant(in_place_index_t<I>, Args&&...); template<size_t I, class U, class... Args> constexpr explicit variant(in_place_index_t<I>, initializer_list<U>, Args&&...); // destructor constexpr ~variant(); // assignment constexpr variant& operator=(const variant&); constexpr variant& operator=(variant&&) noexcept(/* see description */); template<class T> constexpr variant& operator=(T&&) noexcept(/* see description */); // modifiers template<class T, class... Args> constexpr T& emplace(Args&&...); template<class T, class U, class... Args> constexpr T& emplace(initializer_list<U>, Args&&...); template<size_t I, class... Args> constexpr variant_alternative_t<I, variant<Types...>>& emplace(Args&&...); template<size_t I, class U, class... Args> constexpr variant_alternative_t<I, variant<Types...>>& emplace(initializer_list<U>, Args&&...); // value status constexpr bool valueless_by_exception() const noexcept; constexpr size_t index() const noexcept; // swap constexpr void swap(variant&) noexcept(/* see description */); }; } ``` #### Class `[std::monostate](../utility/variant/monostate "cpp/utility/variant/monostate")` ``` struct monostate{}; ``` #### Class `[std::bad\_variant\_access](../utility/variant/bad_variant_access "cpp/utility/variant/bad variant access")` ``` class bad_variant_access : public exception { public: // see [exception] for the specification of the special member functions const char* what() const noexcept override; }; ```
programming_docs
cpp Standard library header <cstddef> Standard library header <cstddef> ================================= This header was originally in the C standard library as `<stddef.h>`. This header is part of the [utility](../utility "cpp/utility") library. | | | --- | | Macros | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | [offsetof](../types/offsetof "cpp/types/offsetof") | byte offset from the beginning of a standard-layout type to specified member (function macro) | | Types | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | | [ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t") | signed integer type returned when subtracting two pointers (typedef) | | [nullptr\_t](../types/nullptr_t "cpp/types/nullptr t") (C++11) | the type of the null pointer literal [`nullptr`](../language/nullptr "cpp/language/nullptr") (typedef) | | [max\_align\_t](../types/max_align_t "cpp/types/max align t") (C++11) | trivial type with alignment requirement as great as any other scalar type (typedef) | | [byte](../types/byte "cpp/types/byte") (C++17) | the byte type (enum) | ### Synopsis ``` namespace std { using ptrdiff_t = /* see description */; using size_t = /* see description */; using max_align_t = /* see description */; using nullptr_t = decltype(nullptr); enum class byte : unsigned char {}; // byte type operations template<class IntType> constexpr byte& operator<<=(byte& b, IntType shift) noexcept; template<class IntType> constexpr byte operator<<(byte b, IntType shift) noexcept; template<class IntType> constexpr byte& operator>>=(byte& b, IntType shift) noexcept; template<class IntType> constexpr byte operator>>(byte b, IntType shift) noexcept; constexpr byte& operator|=(byte& l, byte r) noexcept; constexpr byte operator|(byte l, byte r) noexcept; constexpr byte& operator&=(byte& l, byte r) noexcept; constexpr byte operator&(byte l, byte r) noexcept; constexpr byte& operator^=(byte& l, byte r) noexcept; constexpr byte operator^(byte l, byte r) noexcept; constexpr byte operator~(byte b) noexcept; template<class IntType> constexpr IntType to_integer(byte b) noexcept; } #define NULL /* see description */ #define offsetof(P, D) /* see description */ ``` ### Notes * `[NULL](../types/null "cpp/types/NULL")` is also defined in the following headers: + [`<clocale>`](clocale "cpp/header/clocale") + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstring>`](cstring "cpp/header/cstring") + [`<cstdio>`](cstdio "cpp/header/cstdio") + [`<cstdlib>`](cstdlib "cpp/header/cstdlib") + [`<cwchar>`](cwchar "cpp/header/cwchar") * `[std::size\_t](../types/size_t "cpp/types/size t")` is also defined in the following headers: + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstring>`](cstring "cpp/header/cstring") + [`<cstdio>`](cstdio "cpp/header/cstdio") + [`<cwchar>`](cwchar "cpp/header/cwchar") + [`<cuchar>`](cuchar "cpp/header/cuchar") (since C++17) cpp Standard library header <csetjmp> Standard library header <csetjmp> ================================= This header was originally in the C standard library as `<setjmp.h>`. This header is part of the [program support](../utility/program "cpp/utility/program") library. | | | --- | | Types | | [jmp\_buf](../utility/program/jmp_buf "cpp/utility/program/jmp buf") | execution context type (typedef) | | Macros | | [setjmp](../utility/program/setjmp "cpp/utility/program/setjmp") | saves the context (function macro) | | Functions | | [longjmp](../utility/program/longjmp "cpp/utility/program/longjmp") | jumps to specified location (function) | ### Synopsis ``` namespace std { using jmp_buf = /* see description */ ; [[noreturn]] void longjmp(jmp_buf env, int val); } #define setjmp(env) /* see description */ ``` cpp Standard library header <ratio> (C++11) Standard library header <ratio> (C++11) ======================================= This header is part of the [compile-time rational arithmetic](../numeric/ratio "cpp/numeric/ratio") library. | | | --- | | Classes | | [ratio](../numeric/ratio/ratio "cpp/numeric/ratio/ratio") (C++11) | represents exact rational fraction (class template) | | Arithmetic | | [ratio\_add](../numeric/ratio/ratio_add "cpp/numeric/ratio/ratio add") (C++11) | adds two `ratio` objects at compile-time (alias template) | | [ratio\_subtract](../numeric/ratio/ratio_subtract "cpp/numeric/ratio/ratio subtract") (C++11) | subtracts two `ratio` objects at compile-time (alias template) | | [ratio\_multiply](../numeric/ratio/ratio_multiply "cpp/numeric/ratio/ratio multiply") (C++11) | multiplies two `ratio` objects at compile-time (alias template) | | [ratio\_divide](../numeric/ratio/ratio_divide "cpp/numeric/ratio/ratio divide") (C++11) | divides two `ratio` objects at compile-time (alias template) | | Comparison | | [ratio\_equal](../numeric/ratio/ratio_equal "cpp/numeric/ratio/ratio equal") (C++11) | compares two `ratio` objects for equality at compile-time (class template) | | [ratio\_not\_equal](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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) | | Constants | | `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 | ### Synopsis ``` namespace std { // class template ratio template <intmax_t N, intmax_t D = 1> class ratio { public: typedef ratio<num, den> type; static constexpr intmax_t num; static constexpr intmax_t den; }; // ratio arithmetic template <class R1, class R2> using ratio_add = /*ratio*/; template <class R1, class R2> using ratio_subtract = /*ratio*/; template <class R1, class R2> using ratio_multiply = /*ratio*/; template <class R1, class R2> using ratio_divide = /*ratio*/; // ratio comparison template <class R1, class R2> struct ratio_equal; template <class R1, class R2> struct ratio_not_equal; template <class R1, class R2> struct ratio_less; template <class R1, class R2> struct ratio_less_equal; template <class R1, class R2> struct ratio_greater; template <class R1, class R2> struct ratio_greater_equal; // convenience SI typedefs typedef ratio<1, 1000000000000000000000000> yocto; typedef ratio<1, 1000000000000000000000> zepto; typedef ratio<1, 1000000000000000000> atto; typedef ratio<1, 1000000000000000> femto; typedef ratio<1, 1000000000000> pico; typedef ratio<1, 1000000000> nano; typedef ratio<1, 1000000> micro; typedef ratio<1, 1000> milli; typedef ratio<1, 100> centi; typedef ratio<1, 10> deci; typedef ratio< 10, 1> deca; typedef ratio< 100, 1> hecto; typedef ratio< 1000, 1> kilo; typedef ratio< 1000000, 1> mega; typedef ratio< 1000000000, 1> giga; typedef ratio< 1000000000000, 1> tera; typedef ratio< 1000000000000000, 1> peta; typedef ratio< 1000000000000000000, 1> exa; typedef ratio< 1000000000000000000000, 1> zetta; typedef ratio<1000000000000000000000000, 1> yotta; } ``` cpp Standard library header <cstdlib> Standard library header <cstdlib> ================================= This header was originally in the C standard library as `<stdlib.h>`. This header provides miscellaneous utilities. Symbols defined here are used by several library components. | | | --- | | Types | | [div\_t](../numeric/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](../numeric/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](../numeric/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) | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | | Macro constants | | [EXIT\_SUCCESSEXIT\_FAILURE](../utility/program/exit_status "cpp/utility/program/EXIT status") | indicates program execution execution status (macro constant) | | MB\_CUR\_MAX | maximum number of bytes in a multibyte character with the current locale (macro constant) | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | [RAND\_MAX](../numeric/random/rand_max "cpp/numeric/random/RAND MAX") | maximum possible value generated by `[std::rand](../numeric/random/rand "cpp/numeric/random/rand")` (macro constant) | | Functions | | Process control | | [abort](../utility/program/abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](../utility/program/exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [quick\_exit](../utility/program/quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [\_Exit](../utility/program/_exit "cpp/utility/program/ Exit") (C++11) | causes normal program termination without cleaning up (function) | | [atexit](../utility/program/atexit "cpp/utility/program/atexit") | registers a function to be called on `[std::exit()](../utility/program/exit "cpp/utility/program/exit")` invocation (function) | | [at\_quick\_exit](../utility/program/at_quick_exit "cpp/utility/program/at quick exit") (C++11) | registers a function to be called on `[std::quick\_exit](../utility/program/quick_exit "cpp/utility/program/quick exit")` invocation (function) | | [system](../utility/program/system "cpp/utility/program/system") | calls the host environment's command processor (function) | | [getenv](../utility/program/getenv "cpp/utility/program/getenv") | access to the list of environment variables (function) | | Memory management | | [malloc](../memory/c/malloc "cpp/memory/c/malloc") | allocates memory (function) | | [aligned\_alloc](../memory/c/aligned_alloc "cpp/memory/c/aligned alloc") (C++17) | allocates aligned memory (function) | | [calloc](../memory/c/calloc "cpp/memory/c/calloc") | allocates and zeroes memory (function) | | [realloc](../memory/c/realloc "cpp/memory/c/realloc") | expands or shrinks previously allocated memory block (function) | | [free](../memory/c/free "cpp/memory/c/free") | deallocates previously allocated memory (function) | | Numeric string conversion | | [atof](../string/byte/atof "cpp/string/byte/atof") | converts a byte string to a floating point value (function) | | [atoiatolatoll](../string/byte/atoi "cpp/string/byte/atoi") (C++11) | converts a byte string to an integer value (function) | | [strtolstrtoll](../string/byte/strtol "cpp/string/byte/strtol") (C++11) | converts a byte string to an integer value (function) | | [strtoulstrtoull](../string/byte/strtoul "cpp/string/byte/strtoul") (C++11) | converts a byte string to an unsigned integer value (function) | | [strtofstrtodstrtold](../string/byte/strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) | | Wide string manipulation | | [mblen](../string/multibyte/mblen "cpp/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) | | [mbtowc](../string/multibyte/mbtowc "cpp/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) | | [wctomb](../string/multibyte/wctomb "cpp/string/multibyte/wctomb") | converts a wide character to its multibyte representation (function) | | [mbstowcs](../string/multibyte/mbstowcs "cpp/string/multibyte/mbstowcs") | converts a narrow multibyte character string to wide string (function) | | [wcstombs](../string/multibyte/wcstombs "cpp/string/multibyte/wcstombs") | converts a wide string to narrow multibyte character string (function) | | Miscellaneous algorithms and math | | [rand](../numeric/random/rand "cpp/numeric/random/rand") | generates a pseudo-random number (function) | | [srand](../numeric/random/srand "cpp/numeric/random/srand") | seeds pseudo-random number generator (function) | | [qsort](../algorithm/qsort "cpp/algorithm/qsort") | sorts a range of elements with unspecified type (function) | | [bsearch](../algorithm/bsearch "cpp/algorithm/bsearch") | searches an array for an element of unspecified type (function) | | [abs(int)labsllabs](../numeric/math/abs "cpp/numeric/math/abs") (C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) | | [div(int)ldivlldiv](../numeric/math/div "cpp/numeric/math/div") (C++11) | computes quotient and remainder of integer division (function) | ### Synopsis ``` namespace std { using size_t = /* see description */; using div_t = /* see description */; using ldiv_t = /* see description */; using lldiv_t = /* see description */; } #define NULL /* see description */ #define EXIT_FAILURE /* see description */ #define EXIT_SUCCESS /* see description */ #define RAND_MAX /* see description */ #define MB_CUR_MAX /* see description */ namespace std { // Exposition-only function type aliases extern "C" using /*c-atexit-handler*/ = void(); // exposition only extern "C++" using /*atexit-handler*/ = void(); // exposition only extern "C" using /*c-compare-pred*/ = int(const void*, const void*); // exposition only extern "C++" using /*compare-pred*/ = int(const void*, const void*); // exposition only // start and termination [[noreturn]] void abort() noexcept; int atexit(/*c-atexit-handler*/* func) noexcept; int atexit(/*atexit-handler*/* func) noexcept; int at_quick_exit(/*c-atexit-handler*/* func) noexcept; int at_quick_exit(/*atexit-handler*/* func) noexcept; [[noreturn]] void exit(int status); [[noreturn]] void _Exit(int status) noexcept; [[noreturn]] void quick_exit(int status) noexcept; char* getenv(const char* name); int system(const char* string); // C library memory allocation void* aligned_alloc(size_t alignment, size_t size); void* calloc(size_t nmemb, size_t size); void free(void* ptr); void* malloc(size_t size); void* realloc(void* ptr, size_t size); double atof(const char* nptr); int atoi(const char* nptr); long int atol(const char* nptr); long long int atoll(const char* nptr); double strtod(const char* nptr, char** endptr); float strtof(const char* nptr, char** endptr); long double strtold(const char* nptr, char** endptr); long int strtol(const char* nptr, char** endptr, int base); long long int strtoll(const char* nptr, char** endptr, int base); unsigned long int strtoul(const char* nptr, char** endptr, int base); unsigned long long int strtoull(const char* nptr, char** endptr, int base); // multibyte / wide string and character conversion functions int mblen(const char* s, size_t n); int mbtowc(wchar_t* pwc, const char* s, size_t n); int wctomb(char* s, wchar_t wchar); size_t mbstowcs(wchar_t* pwcs, const char* s, size_t n); size_t wcstombs(char* s, const wchar_t* pwcs, size_t n); // C standard library algorithms void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, /*c-compare-pred*/* compar); void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, /*compare-pred*/* compar); void qsort(void* base, size_t nmemb, size_t size, /*c-compare-pred*/* compar); void qsort(void* base, size_t nmemb, size_t size, /*compare-pred*/* compar); // low-quality random number generation int rand(); void srand(unsigned int seed); // absolute values constexpr int abs(int j); constexpr long int abs(long int j); constexpr long long int abs(long long int j); constexpr float abs(float j); constexpr double abs(double j); constexpr long double abs(long double j); constexpr long int labs(long int j); constexpr long long int llabs(long long int j); constexpr div_t div(int numer, int denom); constexpr ldiv_t div(long int numer, long int denom); constexpr lldiv_t div(long long int numer, long long int denom); constexpr ldiv_t ldiv(long int numer, long int denom); constexpr lldiv_t lldiv(long long int numer, long long int denom); } ``` ### See also * [Program support utilities](../utility/program "cpp/utility/program") * [Pseudo-random number generation](../numeric/random "cpp/numeric/random") * [Common mathematical functions](../numeric/math "cpp/numeric/math") * [Mathematical special functions](../numeric/special_functions "cpp/numeric/special functions") * [C memory management library](../memory/c "cpp/memory/c") * [Null-terminated byte strings](../string/byte "cpp/string/byte") * [Null-terminated multibyte strings](../string/multibyte "cpp/string/multibyte") * [Algorithms library](../algorithm "cpp/algorithm")
programming_docs
cpp Standard library header <optional> (C++17) Standard library header <optional> (C++17) ========================================== | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [optional](../utility/optional "cpp/utility/optional") (C++17) | a wrapper that may or may not hold an object (class template) | | [bad\_optional\_access](../utility/optional/bad_optional_access "cpp/utility/optional/bad optional access") (C++17) | exception indicating checked access to an optional that doesn't contain a value (class) | | [std::hash<std::optional>](../utility/optional/hash "cpp/utility/optional/hash") (C++17) | specializes the `[std::hash](../utility/hash "cpp/utility/hash")` algorithm (class template specialization) | | [nullopt\_t](../utility/optional/nullopt_t "cpp/utility/optional/nullopt t") (C++17) | indicator of optional type with uninitialized state (class) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Constants | | [nullopt](../utility/optional/nullopt "cpp/utility/optional/nullopt") (C++17) | an object of type `nullopt_t` (constant) | | Functions | | Comparison | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../utility/optional/operator_cmp "cpp/utility/optional/operator cmp") (C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20) | compares `optional` objects (function template) | | Specialized algorithms | | [std::swap(std::optional)](../utility/optional/swap2 "cpp/utility/optional/swap2") (C++17) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [make\_optional](../utility/optional/make_optional "cpp/utility/optional/make optional") (C++17) | creates an `optional` object (function template) | ### Synopsis ``` #include <compare> namespace std { // class template optional template<class T> class optional; // no-value state indicator struct nullopt_t{/* see description */}; inline constexpr nullopt_t nullopt(/* unspecified */); // class bad_optional_access class bad_optional_access; // relational operators template<class T, class U> constexpr bool operator==(const optional<T>&, const optional<U>&); template<class T, class U> constexpr bool operator!=(const optional<T>&, const optional<U>&); template<class T, class U> constexpr bool operator<(const optional<T>&, const optional<U>&); template<class T, class U> constexpr bool operator>(const optional<T>&, const optional<U>&); template<class T, class U> constexpr bool operator<=(const optional<T>&, const optional<U>&); template<class T, class U> constexpr bool operator>=(const optional<T>&, const optional<U>&); template<class T, three_way_comparable_with<T> U> constexpr compare_three_way_result_t<T,U> operator<=>(const optional<T>&, const optional<U>&); // comparison with nullopt template<class T> constexpr bool operator==(const optional<T>&, nullopt_t) noexcept; template<class T> constexpr strong_ordering operator<=>(const optional<T>&, nullopt_t) noexcept; // comparison with T template<class T, class U> constexpr bool operator==(const optional<T>&, const U&); template<class T, class U> constexpr bool operator==(const T&, const optional<U>&); template<class T, class U> constexpr bool operator!=(const optional<T>&, const U&); template<class T, class U> constexpr bool operator!=(const T&, const optional<U>&); template<class T, class U> constexpr bool operator<(const optional<T>&, const U&); template<class T, class U> constexpr bool operator<(const T&, const optional<U>&); template<class T, class U> constexpr bool operator>(const optional<T>&, const U&); template<class T, class U> constexpr bool operator>(const T&, const optional<U>&); template<class T, class U> constexpr bool operator<=(const optional<T>&, const U&); template<class T, class U> constexpr bool operator<=(const T&, const optional<U>&); template<class T, class U> constexpr bool operator>=(const optional<T>&, const U&); template<class T, class U> constexpr bool operator>=(const T&, const optional<U>&); template<class T, three_way_comparable_with<T> U> constexpr compare_three_way_result_t<T,U> operator<=>(const optional<T>&, const U&); // specialized algorithms template<class T> constexpr void swap(optional<T>&, optional<T>&) noexcept(/* see description */); template<class T> constexpr optional</* see description */> make_optional(T&&); template<class T, class... Args> constexpr optional<T> make_optional(Args&&... args); template<class T, class U, class... Args> constexpr optional<T> make_optional(initializer_list<U> il, Args&&... args); // hash support template<class T> struct hash; template<class T> struct hash<optional<T>>; } ``` #### Class template `[std::optional](../utility/optional "cpp/utility/optional")` ``` namespace std { template<class T> class optional { public: using value_type = T; // constructors constexpr optional() noexcept; constexpr optional(nullopt_t) noexcept; constexpr optional(const optional&); constexpr optional(optional&&) noexcept(/* see description */); template<class... Args> constexpr explicit optional(in_place_t, Args&&...); template<class U, class... Args> constexpr explicit optional(in_place_t, initializer_list<U>, Args&&...); template<class U = T> constexpr explicit(/* see description */) optional(U&&); template<class U> constexpr explicit(/* see description */) optional(const optional<U>&); template<class U> constexpr explicit(/* see description */) optional(optional<U>&&); // destructor constexpr ~optional(); // assignment constexpr optional& operator=(nullopt_t) noexcept; constexpr optional& operator=(const optional&); constexpr optional& operator=(optional&&) noexcept(/* see description */); template<class U = T> constexpr optional& operator=(U&&); template<class U> constexpr optional& operator=(const optional<U>&); template<class U> constexpr optional& operator=(optional<U>&&); template<class... Args> constexpr T& emplace(Args&&...); template<class U, class... Args> constexpr T& emplace(initializer_list<U>, Args&&...); // swap constexpr void swap(optional&) noexcept(/* see description */); // observers constexpr const T* operator->() const noexcept; constexpr T* operator->() noexcept; constexpr const T& operator*() const& noexcept; constexpr T& operator*() & noexcept; constexpr T&& operator*() && noexcept; constexpr const T&& operator*() const&& noexcept; constexpr explicit operator bool() const noexcept; constexpr bool has_value() const noexcept; constexpr const T& value() const&; constexpr T& value() &; constexpr T&& value() &&; constexpr const T&& value() const&&; template<class U> constexpr T value_or(U&&) const&; template<class U> constexpr T value_or(U&&) &&; // monadic operations template <class F> constexpr auto and_then(F&& f) &; template <class F> constexpr auto and_then(F&& f) &&; template <class F> constexpr auto and_then(F&& f) const&; template <class F> constexpr auto and_then(F&& f) const&&; template <class F> constexpr auto transform(F&& f) &; template <class F> constexpr auto transform(F&& f) &&; template <class F> constexpr auto transform(F&& f) const&; template <class F> constexpr auto transform(F&& f) const&&; template <class F> constexpr optional or_else(F&& f) &&; template <class F> constexpr optional or_else(F&& f) const&; // modifiers constexpr void reset() noexcept; private: T *val; // exposition only }; template<class T> optional(T) -> optional<T>; } ``` cpp Standard library header <codecvt> (C++11)(deprecated in C++17) Standard library header <codecvt> (C++11)(deprecated in C++17) ============================================================== This header is part of the [Localization](../locale "cpp/locale") library. | | | --- | | Classes | | [codecvt\_utf8](../locale/codecvt_utf8 "cpp/locale/codecvt utf8") (C++11)(deprecated in C++17) | converts between UTF-8 and UCS2/UCS4 (class template) | | [codecvt\_utf16](../locale/codecvt_utf16 "cpp/locale/codecvt utf16") (C++11)(deprecated in C++17) | converts between UTF-16 and UCS2/UCS4 (class template) | | [codecvt\_utf8\_utf16](../locale/codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16") (C++11)(deprecated in C++17) | converts between UTF-8 and UTF-16 (class template) | | [codecvt\_mode](../locale/codecvt_mode "cpp/locale/codecvt mode") (C++11)(deprecated in C++17) | tags to alter behavior of the standard codecvt facets (enum) | ### Synopsis ``` namespace std { enum codecvt_mode { consume_header = 4, generate_header = 2, little_endian = 1 }; template<class Elem, unsigned long Maxcode = 0x10ffff, codecvt_mode Mode = (codecvt_mode)0> class codecvt_utf8; template<class Elem, unsigned long Maxcode = 0x10ffff, codecvt_mode Mode = (codecvt_mode)0> class codecvt_utf16; template<class Elem, unsigned long Maxcode = 0x10ffff, codecvt_mode Mode = (codecvt_mode)0> class codecvt_utf8_utf16; } ``` #### Class `[std::codecvt\_utf8](../locale/codecvt_utf8 "cpp/locale/codecvt utf8")` ``` namespace std { template<class Elem, unsigned long Maxcode = 0x10ffff, codecvt_mode Mode = (codecvt_mode)0> class codecvt_utf8 : public codecvt<Elem, char, mbstate_t> { public: explicit codecvt_utf8(size_t refs = 0); ~codecvt_utf8(); }; } ``` #### Class `[std::codecvt\_utf16](../locale/codecvt_utf16 "cpp/locale/codecvt utf16")` ``` namespace std { template<class Elem, unsigned long Maxcode = 0x10ffff, codecvt_mode Mode = (codecvt_mode)0> class codecvt_utf16 : public codecvt<Elem, char, mbstate_t> { public: explicit codecvt_utf16(size_t refs = 0); ~codecvt_utf16(); }; } ``` #### Class `[std::codecvt\_utf8\_utf16](../locale/codecvt_utf8_utf16 "cpp/locale/codecvt utf8 utf16")` ``` namespace std { template<class Elem, unsigned long Maxcode = 0x10ffff, codecvt_mode Mode = (codecvt_mode)0> class codecvt_utf8_utf16 : public codecvt<Elem, char, mbstate_t> { public: explicit codecvt_utf8_utf16(size_t refs = 0); ~codecvt_utf8_utf16(); }; } ``` cpp Standard library header <cstdbool> (C++11)(until C++20), <stdbool.h> (C++11) Standard library header <cstdbool> (C++11)(until C++20), <stdbool.h> (C++11) ============================================================================ This header was originally in the C standard library as `<stdbool.h>`. Compatibility header, in C defines [`true`](../keyword/true "cpp/keyword/true"), [`false`](../keyword/false "cpp/keyword/false") and [`bool`](../keyword/bool "cpp/keyword/bool") which are keywords in C++. | | | --- | | Macros | | \_\_bool\_true\_false\_are\_defined (C++11) | C compatibility macro constant, expands to integer literal `1` (macro constant) | ### Notes `<cstdbool>` is deprecated in C++17 and removed in C++20. Corresponding `<stdbool.h>` is still available in C++20. cpp Standard library header <exception> Standard library header <exception> =================================== This header is part of the [error handling](../error "cpp/error") library. | | | --- | | Types | | [exception](../error/exception "cpp/error/exception") | base class for exceptions thrown by the standard library components (class) | | [nested\_exception](../error/nested_exception "cpp/error/nested exception") (C++11) | a mixin type to capture and store current exceptions (class) | | [bad\_exception](../error/bad_exception "cpp/error/bad exception") | exception thrown when `[std::current\_exception](../error/current_exception "cpp/error/current exception")` fails to copy the exception object (class) | | [unexpected\_handler](../error/unexpected_handler "cpp/error/unexpected handler") (removed in C++17) | the type of the function called by `[std::unexpected](../error/unexpected "cpp/error/unexpected")` (typedef) | | [terminate\_handler](../error/terminate_handler "cpp/error/terminate handler") | the type of the function called by `[std::terminate](../error/terminate "cpp/error/terminate")` (typedef) | | [exception\_ptr](../error/exception_ptr "cpp/error/exception ptr") (C++11) | shared pointer type for handling exception objects (typedef) | | Functions | | [unexpected](../error/unexpected "cpp/error/unexpected") (removed in C++17) | function called when dynamic exception specification is violated (function) | | [uncaught\_exceptionuncaught\_exceptions](../error/uncaught_exception "cpp/error/uncaught exception") (removed in C++20)(C++17) | checks if exception handling is currently in progress (function) | | [make\_exception\_ptr](../error/make_exception_ptr "cpp/error/make exception ptr") (C++11) | creates an `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` from an exception object (function template) | | [current\_exception](../error/current_exception "cpp/error/current exception") (C++11) | captures the current exception in a `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` (function) | | [rethrow\_exception](../error/rethrow_exception "cpp/error/rethrow exception") (C++11) | throws the exception from an `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` (function) | | [throw\_with\_nested](../error/throw_with_nested "cpp/error/throw with nested") (C++11) | throws its argument with `[std::nested\_exception](../error/nested_exception "cpp/error/nested exception")` mixed in (function template) | | [rethrow\_if\_nested](../error/rethrow_if_nested "cpp/error/rethrow if nested") (C++11) | throws the exception from a `[std::nested\_exception](../error/nested_exception "cpp/error/nested exception")` (function template) | | [terminate](../error/terminate "cpp/error/terminate") | function called when exception handling fails (function) | | [get\_terminate](../error/get_terminate "cpp/error/get terminate") (C++11) | obtains the current terminate\_handler (function) | | [set\_terminate](../error/set_terminate "cpp/error/set terminate") | changes the function to be called by `[std::terminate](../error/terminate "cpp/error/terminate")` (function) | | [get\_unexpected](../error/get_unexpected "cpp/error/get unexpected") (C++11)(removed in C++17) | obtains the current unexpected\_handler (function) | | [set\_unexpected](../error/set_unexpected "cpp/error/set unexpected") (removed in C++17) | changes the function to be called by `[std::unexpected](../error/unexpected "cpp/error/unexpected")` (function) | ### Synopsis ``` namespace std { class exception; class bad_exception; class nested_exception; using terminate_handler = void (*)(); terminate_handler get_terminate() noexcept; terminate_handler set_terminate(terminate_handler f) noexcept; [[noreturn]] void terminate() noexcept; int uncaught_exceptions() noexcept; using exception_ptr = /* unspecified */; exception_ptr current_exception() noexcept; [[noreturn]] void rethrow_exception(exception_ptr p); template<class E> exception_ptr make_exception_ptr(E e) noexcept; template<class T> [[noreturn]] void throw_with_nested(T&& t); template<class E> void rethrow_if_nested(const E& e); } ``` #### Class `[std::exception](../error/exception "cpp/error/exception")` ``` namespace std { class exception { public: exception() noexcept; exception(const exception&) noexcept; exception& operator=(const exception&) noexcept; virtual ~exception(); virtual const char* what() const noexcept; }; } ``` #### Class `[std::bad\_exception](../error/bad_exception "cpp/error/bad exception")` ``` namespace std { class bad_exception : public exception { public: // see [exception] for the specification of the special member functions const char* what() const noexcept override; }; } ``` #### Class `[std::nested\_exception](../error/nested_exception "cpp/error/nested exception")` ``` namespace std { class nested_exception { public: nested_exception() noexcept; nested_exception(const nested_exception&) noexcept = default; nested_exception& operator=(const nested_exception&) noexcept = default; virtual ~nested_exception() = default; // access functions [[noreturn]] void rethrow_nested() const; exception_ptr nested_ptr() const noexcept; }; template<class T> [[noreturn]] void throw_with_nested(T&& t); template<class E> void rethrow_if_nested(const E& e); } ``` ### See also * [Error handling](../error "cpp/error") cpp Standard library header <source_location> (C++20) Standard library header <source\_location> (C++20) ================================================== This header is part of the [utility](../utility "cpp/utility") library. | | | --- | | Classes | | [source\_location](../utility/source_location "cpp/utility/source location") (C++20) | A class representing information about the source code, such as file names, line numbers, and function names (class) | ### Synopsis ``` namespace std { struct source_location; } ``` #### Class `[std::source\_location](../utility/source_location "cpp/utility/source location")` ``` namespace std { struct source_location { // source location construction static consteval source_location current() noexcept; constexpr source_location() noexcept; // source location field access constexpr uint_least32_t line() const noexcept; constexpr uint_least32_t column() const noexcept; constexpr const char* file_name() const noexcept; constexpr const char* function_name() const noexcept; private: uint_least32_t line_; // exposition only uint_least32_t column_; // exposition only const char* file_name_; // exposition only const char* function_name_; // exposition only }; } ``` cpp Standard library header <tuple> (C++11) Standard library header <tuple> (C++11) ======================================= This header is part of the [general utility](../utility "cpp/utility") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [tuple](../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | | [tuple\_size](../utility/tuple_size "cpp/utility/tuple size") (C++11) | obtains the number of elements of a tuple-like type (class template) | | [tuple\_element](../utility/tuple_element "cpp/utility/tuple element") (C++11) | obtains the element types of a tuple-like type (class template) | | [std::tuple\_size<std::tuple>](../utility/tuple/tuple_size "cpp/utility/tuple/tuple size") (C++11) | obtains the size of `tuple` at compile time (class template specialization) | | [std::tuple\_element<std::tuple>](../utility/tuple/tuple_element "cpp/utility/tuple/tuple element") (C++11) | obtains the type of the specified element (class template specialization) | | [std::uses\_allocator<std::tuple>](../utility/tuple/uses_allocator "cpp/utility/tuple/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | Constants | | [ignore](../utility/tuple/ignore "cpp/utility/tuple/ignore") (C++11) | placeholder to skip an element when unpacking a `tuple` using [`tie`](../utility/tuple/tie "cpp/utility/tuple/tie") (constant) | | Functions | | [make\_tuple](../utility/tuple/make_tuple "cpp/utility/tuple/make tuple") (C++11) | creates a `tuple` object of the type defined by the argument types (function template) | | [tie](../utility/tuple/tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../utility/tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) | | [forward\_as\_tuple](../utility/tuple/forward_as_tuple "cpp/utility/tuple/forward as tuple") (C++11) | creates a `tuple` of [forwarding references](../language/reference#Forwarding_references "cpp/language/reference") (function template) | | [tuple\_cat](../utility/tuple/tuple_cat "cpp/utility/tuple/tuple cat") (C++11) | creates a `tuple` by concatenating any number of tuples (function template) | | [std::get(std::tuple)](../utility/tuple/get "cpp/utility/tuple/get") (C++11) | tuple accesses specified element (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../utility/tuple/operator_cmp "cpp/utility/tuple/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the tuple (function template) | | [std::swap(std::tuple)](../utility/tuple/swap2 "cpp/utility/tuple/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [apply](../utility/apply "cpp/utility/apply") (C++17) | calls a function with a tuple of arguments (function template) | | [make\_from\_tuple](../utility/make_from_tuple "cpp/utility/make from tuple") (C++17) | Construct an object with a tuple of arguments (function template) | ### Synopsis ``` #include <compare> namespace std { // class template tuple template<class... Types> class tuple; // tuple creation functions inline constexpr /* unspecified */ ignore; template<class... TTypes> constexpr tuple<unwrap_ref_decay_t<TTypes>...> make_tuple(TTypes&&...); template<class... TTypes> constexpr tuple<TTypes&&...> forward_as_tuple(TTypes&&...) noexcept; template<class... TTypes> constexpr tuple<TTypes&...> tie(TTypes&...) noexcept; template<class... Tuples> constexpr tuple<CTypes...> tuple_cat(Tuples&&...); // calling a function with a tuple of arguments template<class F, class Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t); template<class T, class Tuple> constexpr T make_from_tuple(Tuple&& t); // tuple helper classes template<class T> struct tuple_size; // not defined template<class T> struct tuple_size<const T>; template<class... Types> struct tuple_size<tuple<Types...>>; template<size_t I, class T> struct tuple_element; // not defined template<size_t I, class T> struct tuple_element<I, const T>; template<size_t I, class... Types> struct tuple_element<I, tuple<Types...>>; template<size_t I, class T> using tuple_element_t = typename tuple_element<I, T>::type; // element access template<size_t I, class... Types> constexpr tuple_element_t<I, tuple<Types...>>& get(tuple<Types...>&) noexcept; template<size_t I, class... Types> constexpr tuple_element_t<I, tuple<Types...>>&& get(tuple<Types...>&&) noexcept; template<size_t I, class... Types> constexpr const tuple_element_t<I, tuple<Types...>>& get(const tuple<Types...>&) noexcept; template<size_t I, class... Types> constexpr const tuple_element_t<I, tuple<Types...>>&& get(const tuple<Types...>&&) noexcept; template<class T, class... Types> constexpr T& get(tuple<Types...>& t) noexcept; template<class T, class... Types> constexpr T&& get(tuple<Types...>&& t) noexcept; template<class T, class... Types> constexpr const T& get(const tuple<Types...>& t) noexcept; template<class T, class... Types> constexpr const T&& get(const tuple<Types...>&& t) noexcept; // relational operators template<class... TTypes, class... UTypes> constexpr bool operator==(const tuple<TTypes...>&, const tuple<UTypes...>&); template<class... TTypes, class... UTypes> constexpr common_comparison_category_t</*synth-three-way-result*/<TTypes, UTypes>...> operator<=>(const tuple<TTypes...>&, const tuple<UTypes...>&); // allocator-related traits template<class... Types, class Alloc> struct uses_allocator<tuple<Types...>, Alloc>; // specialized algorithms template<class... Types> constexpr void swap(tuple<Types...>& x, tuple<Types...>& y) noexcept(/* see description */); // tuple helper classes template<class T> inline constexpr size_t tuple_size_v = tuple_size<T>::value; } // deprecated namespace std { template<class T> class tuple_size<volatile T>; template<class T> class tuple_size<const volatile T>; template<size_t I, class T> class tuple_element<I, volatile T>; template<size_t I, class T> class tuple_element<I, const volatile T>; } ``` #### Class template `[std::tuple](../utility/tuple "cpp/utility/tuple")` ``` namespace std { template<class... Types> class tuple { public: // tuple construction constexpr explicit(/* see description */) tuple(); constexpr explicit(/* see description */) tuple(const Types&...); // only if sizeof...(Types) >= 1 template<class... UTypes> constexpr explicit(/* see description */) tuple(UTypes&&...); // only if sizeof...(Types) >= 1 tuple(const tuple&) = default; tuple(tuple&&) = default; template<class... UTypes> constexpr explicit(/* see description */) tuple(const tuple<UTypes...>&); template<class... UTypes> constexpr explicit(/* see description */) tuple(tuple<UTypes...>&&); template<class U1, class U2> constexpr explicit(/* see description */) tuple(const pair<U1, U2>&); // only if sizeof...(Types) == 2 template<class U1, class U2> constexpr explicit(/* see description */) tuple(pair<U1, U2>&&); // only if sizeof...(Types) == 2 // allocator-extended constructors template<class Alloc> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a); template<class Alloc> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a, const Types&...); template<class Alloc, class... UTypes> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a, UTypes&&...); template<class Alloc> constexpr tuple(allocator_arg_t, const Alloc& a, const tuple&); template<class Alloc> constexpr tuple(allocator_arg_t, const Alloc& a, tuple&&); template<class Alloc, class... UTypes> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a, const tuple<UTypes...>&); template<class Alloc, class... UTypes> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a, tuple<UTypes...>&&); template<class Alloc, class U1, class U2> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a, const pair<U1, U2>&); template<class Alloc, class U1, class U2> constexpr explicit(/* see description */) tuple(allocator_arg_t, const Alloc& a, pair<U1, U2>&&); // tuple assignment constexpr tuple& operator=(const tuple&); constexpr tuple& operator=(tuple&&) noexcept(/* see description */); template<class... UTypes> constexpr tuple& operator=(const tuple<UTypes...>&); template<class... UTypes> constexpr tuple& operator=(tuple<UTypes...>&&); template<class U1, class U2> constexpr tuple& operator=(const pair<U1, U2>&); // only if sizeof...(Types) == 2 template<class U1, class U2> constexpr tuple& operator=(pair<U1, U2>&&); // only if sizeof...(Types) == 2 // tuple swap constexpr void swap(tuple&) noexcept(/* see description */); }; template<class... UTypes> tuple(UTypes...) -> tuple<UTypes...>; template<class T1, class T2> tuple(pair<T1, T2>) -> tuple<T1, T2>; template<class Alloc, class... UTypes> tuple(allocator_arg_t, Alloc, UTypes...) -> tuple<UTypes...>; template<class Alloc, class T1, class T2> tuple(allocator_arg_t, Alloc, pair<T1, T2>) -> tuple<T1, T2>; template<class Alloc, class... UTypes> tuple(allocator_arg_t, Alloc, tuple<UTypes...>) -> tuple<UTypes...>; } ```
programming_docs
cpp Standard library header <cstdio> Standard library header <cstdio> ================================ This header was originally in the C standard library as `<stdio.h>`. This header is part of the [C-style input/output](../io/c "cpp/io/c") library. | | | --- | | Types | | [FILE](../io/c/file "cpp/io/c/FILE") | object type, capable of holding all information needed to control a C I/O stream (typedef) | | [fpos\_t](../io/c/fpos_t "cpp/io/c/fpos t") | complete non-array object type, capable of uniquely specifying a position in a file, including its multibyte parse state (typedef) | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | | Macros | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | [stdinstdoutstderr](../io/c/std_streams "cpp/io/c/std streams") | expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream (macro constant) | | EOF | integer constant expression of type `int` and negative value (macro constant) | | FOPEN\_MAX | number of files that can be open simultaneously (macro constant) | | FILENAME\_MAX | size needed for an array of `char` to hold the longest supported file name (macro constant) | | BUFSIZ | size of the buffer used by `[std::setbuf](../io/c/setbuf "cpp/io/c/setbuf")` (macro constant) | | \_IOFBF\_IOLBF\_IONBF | argument to `[std::setbuf](../io/c/setbuf "cpp/io/c/setbuf")` indicating fully buffered I/Oargument to `[std::setbuf](../io/c/setbuf "cpp/io/c/setbuf")` indicating line buffered I/Oargument to `[std::setbuf](../io/c/setbuf "cpp/io/c/setbuf")` indicating unbuffered I/O (macro constant) | | SEEK\_SETSEEK\_CURSEEK\_END | argument to `[std::fseek](../io/c/fseek "cpp/io/c/fseek")` indicating seeking from beginning of the fileargument to `[std::fseek](../io/c/fseek "cpp/io/c/fseek")` indicating seeking from the current file positionargument to `[std::fseek](../io/c/fseek "cpp/io/c/fseek")` indicating seeking from end of the file (macro constant) | | TMP\_MAX | maximum number of unique filenames that can be generated by `[std::tmpnam](../io/c/tmpnam "cpp/io/c/tmpnam")` (macro constant) | | L\_tmpnam | size needed for an array of `char` to hold the result of `[std::tmpnam](../io/c/tmpnam "cpp/io/c/tmpnam")` (macro constant) | | Functions | | File access | | [fopen](../io/c/fopen "cpp/io/c/fopen") | opens a file (function) | | [freopen](../io/c/freopen "cpp/io/c/freopen") | open an existing stream with a different name (function) | | [fclose](../io/c/fclose "cpp/io/c/fclose") | closes a file (function) | | [fflush](../io/c/fflush "cpp/io/c/fflush") | synchronizes an output stream with the actual file (function) | | [setbuf](../io/c/setbuf "cpp/io/c/setbuf") | sets the buffer for a file stream (function) | | [setvbuf](../io/c/setvbuf "cpp/io/c/setvbuf") | sets the buffer and its size for a file stream (function) | | Direct input/output | | [fread](../io/c/fread "cpp/io/c/fread") | reads from a file (function) | | [fwrite](../io/c/fwrite "cpp/io/c/fwrite") | writes to a file (function) | | Unformatted input/output | | Narrow character | | [fgetcgetc](../io/c/fgetc "cpp/io/c/fgetc") | gets a character from a file stream (function) | | [fgets](../io/c/fgets "cpp/io/c/fgets") | gets a character string from a file stream (function) | | [fputcputc](../io/c/fputc "cpp/io/c/fputc") | writes a character to a file stream (function) | | [fputs](../io/c/fputs "cpp/io/c/fputs") | writes a character string to a file stream (function) | | [getchar](../io/c/getchar "cpp/io/c/getchar") | reads a character from `[stdin](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [gets](../io/c/gets "cpp/io/c/gets") (deprecated in C++11)(removed in C++14) | reads a character string from `[stdin](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [putchar](../io/c/putchar "cpp/io/c/putchar") | writes a character to `[stdout](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [puts](../io/c/puts "cpp/io/c/puts") | writes a character string to `[stdout](../io/c/std_streams "cpp/io/c/std streams")` (function) | | [ungetc](../io/c/ungetc "cpp/io/c/ungetc") | puts a character back into a file stream (function) | | Formatted input/output | | Narrow/multibyte character | | [scanffscanfsscanf](../io/c/fscanf "cpp/io/c/fscanf") | reads formatted input from `[stdin](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vscanfvfscanfvsscanf](../io/c/vfscanf "cpp/io/c/vfscanf") (C++11)(C++11)(C++11) | reads formatted input from `[stdin](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | [printffprintfsprintfsnprintf](../io/c/fprintf "cpp/io/c/fprintf") (C++11) | prints formatted output to `[stdout](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer (function) | | [vprintfvfprintfvsprintfvsnprintf](../io/c/vfprintf "cpp/io/c/vfprintf") (C++11) | prints formatted output to `[stdout](../io/c/std_streams "cpp/io/c/std streams")`, a file stream or a buffer using variable argument list (function) | | File positioning | | [ftell](../io/c/ftell "cpp/io/c/ftell") | returns the current file position indicator (function) | | [fgetpos](../io/c/fgetpos "cpp/io/c/fgetpos") | gets the file position indicator (function) | | [fseek](../io/c/fseek "cpp/io/c/fseek") | moves the file position indicator to a specific location in a file (function) | | [fsetpos](../io/c/fsetpos "cpp/io/c/fsetpos") | moves the file position indicator to a specific location in a file (function) | | [rewind](../io/c/rewind "cpp/io/c/rewind") | moves the file position indicator to the beginning in a file (function) | | Error handling | | [clearerr](../io/c/clearerr "cpp/io/c/clearerr") | clears errors (function) | | [feof](../io/c/feof "cpp/io/c/feof") | checks for the end-of-file (function) | | [ferror](../io/c/ferror "cpp/io/c/ferror") | checks for a file error (function) | | [perror](../io/c/perror "cpp/io/c/perror") | displays a character string corresponding of the current error to `[stderr](../io/c/std_streams "cpp/io/c/std streams")` (function) | | Operations on files | | [remove](../io/c/remove "cpp/io/c/remove") | erases a file (function) | | [rename](../io/c/rename "cpp/io/c/rename") | renames a file (function) | | [tmpfile](../io/c/tmpfile "cpp/io/c/tmpfile") | creates and opens a temporary, auto-removing file (function) | | [tmpnam](../io/c/tmpnam "cpp/io/c/tmpnam") | returns a unique filename (function) | ### Synopsis ``` namespace std { using size_t = /* see description */; using FILE = /* see description */; using fpos_t = /* see description */; } #define NULL /* see description */ #define _IOFBF /* see description */ #define _IOLBF /* see description */ #define _IONBF /* see description */ #define BUFSIZ /* see description */ #define EOF /* see description */ #define FOPEN_MAX /* see description */ #define FILENAME_MAX /* see description */ #define L_tmpnam /* see description */ #define SEEK_CUR /* see description */ #define SEEK_END /* see description */ #define SEEK_SET /* see description */ #define TMP_MAX /* see description */ #define stderr /* see description */ #define stdin /* see description */ #define stdout /* see description */ namespace std { int remove(const char* filename); int rename(const char* old_p, const char* new_p); FILE* tmpfile(); char* tmpnam(char* s); int fclose(FILE* stream); int fflush(FILE* stream); FILE* fopen(const char* filename, const char* mode); FILE* freopen(const char* filename, const char* mode, FILE* stream); void setbuf(FILE* stream, char* buf); int setvbuf(FILE* stream, char* buf, int mode, size_t size); int fprintf(FILE* stream, const char* format, ...); int fscanf(FILE* stream, const char* format, ...); int printf(const char* format, ...); int scanf(const char* format, ...); int snprintf(char* s, size_t n, const char* format, ...); int sprintf(char* s, const char* format, ...); int sscanf(const char* s, const char* format, ...); int vfprintf(FILE* stream, const char* format, va_list arg); int vfscanf(FILE* stream, const char* format, va_list arg); int vprintf(const char* format, va_list arg); int vscanf(const char* format, va_list arg); int vsnprintf(char* s, size_t n, const char* format, va_list arg); int vsprintf(char* s, const char* format, va_list arg); int vsscanf(const char* s, const char* format, va_list arg); int fgetc(FILE* stream); char* fgets(char* s, int n, FILE* stream); int fputc(int c, FILE* stream); int fputs(const char* s, FILE* stream); int getc(FILE* stream); int getchar(); int putc(int c, FILE* stream); int putchar(int c); int puts(const char* s); int ungetc(int c, FILE* stream); size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream); size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream); int fgetpos(FILE* stream, fpos_t* pos); int fseek(FILE* stream, long int offset, int whence); int fsetpos(FILE* stream, const fpos_t* pos); long int ftell(FILE* stream); void rewind(FILE* stream); void clearerr(FILE* stream); int feof(FILE* stream); int ferror(FILE* stream); void perror(const char* s); } ``` ### Notes * `[NULL](../types/null "cpp/types/NULL")` is also defined in the following headers: + [`<clocale>`](clocale "cpp/header/clocale") + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<cstring>`](cstring "cpp/header/cstring") + [`<cwchar>`](cwchar "cpp/header/cwchar") + [`<cstdlib>`](cstdlib "cpp/header/cstdlib") * `[std::size\_t](../types/size_t "cpp/types/size t")` is also defined in the following headers: + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<cstring>`](cstring "cpp/header/cstring") + [`<cwchar>`](cwchar "cpp/header/cwchar") + [`<cuchar>`](cuchar "cpp/header/cuchar") (since C++17) + [`<cstdlib>`](cstdlib "cpp/header/cstdlib") cpp Standard library header <cerrno> Standard library header <cerrno> ================================ This header was originally in the C standard library as `<errno.h>`. This header is part of the [error handling](../error "cpp/error") library. ### Macros | | | | --- | --- | | [errno](../error/errno "cpp/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) | | E2BIG (C++11) | Argument list too long (macro constant) | | EACCES (C++11) | Permission denied (macro constant) | | EADDRINUSE (C++11) | Address in use (macro constant) | | EADDRNOTAVAIL (C++11) | Address not available (macro constant) | | EAFNOSUPPORT (C++11) | Address family not supported (macro constant) | | EAGAIN (C++11) | Resource unavailable, try again (macro constant) | | EALREADY (C++11) | Connection already in progress (macro constant) | | EBADF (C++11) | Bad file descriptor (macro constant) | | EBADMSG (C++11) | Bad message (macro constant) | | EBUSY (C++11) | Device or resource busy (macro constant) | | ECANCELED (C++11) | Operation canceled (macro constant) | | ECHILD (C++11) | No child processes (macro constant) | | ECONNABORTED (C++11) | Connection aborted (macro constant) | | ECONNREFUSED (C++11) | Connection refused (macro constant) | | ECONNRESET (C++11) | Connection reset (macro constant) | | EDEADLK (C++11) | Resource deadlock would occur (macro constant) | | EDESTADDRREQ (C++11) | Destination address required (macro constant) | | EDOM | Mathematics argument out of domain of function (macro constant) | | EEXIST (C++11) | File exists (macro constant) | | EFAULT (C++11) | Bad address (macro constant) | | EFBIG (C++11) | File too large (macro constant) | | EHOSTUNREACH (C++11) | Host is unreachable (macro constant) | | EIDRM (C++11) | Identifier removed (macro constant) | | EILSEQ (C++11) | Illegal byte sequence (macro constant) | | EINPROGRESS (C++11) | Operation in progress (macro constant) | | EINTR (C++11) | Interrupted function (macro constant) | | EINVAL (C++11) | Invalid argument (macro constant) | | EIO (C++11) | I/O error (macro constant) | | EISCONN (C++11) | Socket is connected (macro constant) | | EISDIR (C++11) | Is a directory (macro constant) | | ELOOP (C++11) | Too many levels of symbolic links (macro constant) | | EMFILE (C++11) | File descriptor value too large (macro constant) | | EMLINK (C++11) | Too many links (macro constant) | | EMSGSIZE (C++11) | Message too large (macro constant) | | ENAMETOOLONG (C++11) | Filename too long (macro constant) | | ENETDOWN (C++11) | Network is down (macro constant) | | ENETRESET (C++11) | Connection aborted by network (macro constant) | | ENETUNREACH (C++11) | Network unreachable (macro constant) | | ENFILE (C++11) | Too many files open in system (macro constant) | | ENOBUFS (C++11) | No buffer space available (macro constant) | | ENODATA (C++11) | No message is available on the STREAM head read queue (macro constant) | | ENODEV (C++11) | No such device (macro constant) | | ENOENT (C++11) | No such file or directory (macro constant) | | ENOEXEC (C++11) | Executable file format error (macro constant) | | ENOLCK (C++11) | No locks available (macro constant) | | ENOLINK (C++11) | Link has been severed (macro constant) | | ENOMEM (C++11) | Not enough space (macro constant) | | ENOMSG (C++11) | No message of the desired type (macro constant) | | ENOPROTOOPT (C++11) | Protocol not available (macro constant) | | ENOSPC (C++11) | No space left on device (macro constant) | | ENOSR (C++11) | No STREAM resources (macro constant) | | ENOSTR (C++11) | Not a STREAM (macro constant) | | ENOSYS (C++11) | Function not supported (macro constant) | | ENOTCONN (C++11) | The socket is not connected (macro constant) | | ENOTDIR (C++11) | Not a directory (macro constant) | | ENOTEMPTY (C++11) | Directory not empty (macro constant) | | ENOTRECOVERABLE (C++11) | State not recoverable (macro constant) | | ENOTSOCK (C++11) | Not a socket (macro constant) | | ENOTSUP (C++11) | Not supported (macro constant) | | ENOTTY (C++11) | Inappropriate I/O control operation (macro constant) | | ENXIO (C++11) | No such device or address (macro constant) | | EOPNOTSUPP (C++11) | Operation not supported on socket (macro constant) | | EOVERFLOW (C++11) | Value too large to be stored in data type (macro constant) | | EOWNERDEAD (C++11) | Previous owner died (macro constant) | | EPERM (C++11) | Operation not permitted (macro constant) | | EPIPE (C++11) | Broken pipe (macro constant) | | EPROTO (C++11) | Protocol error (macro constant) | | EPROTONOSUPPORT (C++11) | Protocol not supported (macro constant) | | EPROTOTYPE (C++11) | Protocol wrong type for socket (macro constant) | | ERANGE | Result too large (macro constant) | | EROFS (C++11) | Read-only file system (macro constant) | | ESPIPE (C++11) | Invalid seek (macro constant) | | ESRCH (C++11) | No such process (macro constant) | | ETIME (C++11) | Stream ioctl() timeout (macro constant) | | ETIMEDOUT (C++11) | Connection timed out (macro constant) | | ETXTBSY (C++11) | Text file busy (macro constant) | | EWOULDBLOCK (C++11) | Operation would block (macro constant) | | EXDEV (C++11) | Cross-device link (macro constant) | ### Notes Although the header `<cerrno>` is based on the C standard library header `errno.h`, the majority of the macros defined by `<cerrno>` were adopted by C++ from the POSIX standard, rather than the C standard library. ### See also * [Description for the error number values](../error/errno_macros "cpp/error/errno macros") cpp Standard library header <cassert> Standard library header <cassert> ================================= This header was originally in the C standard library as `<assert.h>`. This header is part of the [error handling](../error "cpp/error") library. | | | --- | | Macros | | [assert](../error/assert "cpp/error/assert") | aborts the program if the user-specified condition is not `true`. May be disabled for release builds (function macro) | ### Synopsis ``` #define assert(E) /* see description */ ``` cpp Standard library header <list> Standard library header <list> ============================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [list](../container/list "cpp/container/list") | doubly-linked list (class template) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/list/operator_cmp "cpp/container/list/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the list (function template) | | [std::swap(std::list)](../container/list/swap2 "cpp/container/list/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::list)erase\_if(std::list)](../container/list/erase2 "cpp/container/list/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template list template<class T, class Allocator = allocator<T>> class list; template<class T, class Allocator> bool operator==(const list<T, Allocator>& x, const list<T, Allocator>& y); template<class T, class Allocator> /*synth-three-way-result*/<T> operator<=>(const list<T, Allocator>& x, const list<T, Allocator>& y); template<class T, class Allocator> void swap(list<T, Allocator>& x, list<T, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class T, class Allocator, class U> typename list<T, Allocator>::size_type erase(list<T, Allocator>& c, const U& value); template<class T, class Allocator, class Predicate> typename list<T, Allocator>::size_type erase_if(list<T, Allocator>& c, Predicate pred); namespace pmr { template<class T> using list = std::list<T, polymorphic_allocator<T>>; } } ``` #### Class template `[std::list](../container/list "cpp/container/list")` ``` namespace std { template<class T, class Allocator = allocator<T>> class list { public: // types using value_type = T; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // construct/copy/destroy list() : list(Allocator()) { } explicit list(const Allocator&); explicit list(size_type n, const Allocator& = Allocator()); list(size_type n, const T& value, const Allocator& = Allocator()); template<class InputIt> list(InputIt first, InputIt last, const Allocator& = Allocator()); list(const list& x); list(list&& x); list(const list&, const Allocator&); list(list&&, const Allocator&); list(initializer_list<T>, const Allocator& = Allocator()); ~list(); list& operator=(const list& x); list& operator=(list&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value); list& operator=(initializer_list<T>); template<class InputIt> void assign(InputIt first, InputIt last); void assign(size_type n, const T& t); void assign(initializer_list<T>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; void resize(size_type sz); void resize(size_type sz, const T& c); // element access reference front(); const_reference front() const; reference back(); const_reference back() const; // modifiers template<class... Args> reference emplace_front(Args&&... args); template<class... Args> reference emplace_back(Args&&... args); void push_front(const T& x); void push_front(T&& x); void pop_front(); void push_back(const T& x); void push_back(T&& x); void pop_back(); template<class... Args> iterator emplace(const_iterator position, Args&&... args); iterator insert(const_iterator position, const T& x); iterator insert(const_iterator position, T&& x); iterator insert(const_iterator position, size_type n, const T& x); template<class InputIt> iterator insert(const_iterator position, InputIt first, InputIt last); iterator insert(const_iterator position, initializer_list<T> il); iterator erase(const_iterator position); iterator erase(const_iterator position, const_iterator last); void swap(list&) noexcept(allocator_traits<Allocator>::is_always_equal::value); void clear() noexcept; // list operations void splice(const_iterator position, list& x); void splice(const_iterator position, list&& x); void splice(const_iterator position, list& x, const_iterator i); void splice(const_iterator position, list&& x, const_iterator i); void splice(const_iterator position, list& x, const_iterator first, const_iterator last); void splice(const_iterator position, list&& x, const_iterator first, const_iterator last); size_type remove(const T& value); template<class Predicate> size_type remove_if(Predicate pred); size_type unique(); template<class BinaryPredicate> size_type unique(BinaryPredicate binary_pred); void merge(list& x); void merge(list&& x); template<class Compare> void merge(list& x, Compare comp); template<class Compare> void merge(list&& x, Compare comp); void sort(); template<class Compare> void sort(Compare comp); void reverse() noexcept; }; template<class InputIt, class Allocator = allocator</*iter-value-type*/<InputIt>>> list(InputIt, InputIt, Allocator = Allocator()) -> list</*iter-value-type*/<InputIt>, Allocator>; // swap template<class T, class Allocator> void swap(list<T, Allocator>& x, list<T, Allocator>& y) noexcept(noexcept(x.swap(y))); } ```
programming_docs
cpp Standard library header <scoped_allocator> (C++11) Standard library header <scoped\_allocator> (C++11) =================================================== This header is part of the [dynamic memory management](../memory "cpp/memory") library. | | | --- | | Classes | | [scoped\_allocator\_adaptor](../memory/scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor") (C++11) | implements multi-level allocator for multi-level containers (class template) | | Functions | | [operator==operator!=](../memory/scoped_allocator_adaptor/operator_cmp "cpp/memory/scoped allocator adaptor/operator cmp") (removed in C++20) | compares two scoped\_allocator\_adaptor instances (function template) | ### Synopsis ``` namespace std { // class template scoped_allocator_adaptor template<class OuterAlloc, class... InnerAlloc> class scoped_allocator_adaptor; // scoped allocator operators template<class OuterA1, class OuterA2, class... InnerAllocs> bool operator==(const scoped_allocator_adaptor<OuterA1, InnerAllocs...>& a, const scoped_allocator_adaptor<OuterA2, InnerAllocs...>& b) noexcept; } ``` #### Class template `[std::scoped\_allocator\_adaptor](../memory/scoped_allocator_adaptor "cpp/memory/scoped allocator adaptor")` ``` namespace std { template<class OuterAlloc, class... InnerAllocs> class scoped_allocator_adaptor : public OuterAlloc { private: using OuterTraits = allocator_traits<OuterAlloc>; // exposition only scoped_allocator_adaptor<InnerAllocs...> inner; // exposition only public: using outer_allocator_type = OuterAlloc; using inner_allocator_type = /* see description */; using value_type = typename OuterTraits::value_type; using size_type = typename OuterTraits::size_type; using difference_type = typename OuterTraits::difference_type; using pointer = typename OuterTraits::pointer; using const_pointer = typename OuterTraits::const_pointer; using void_pointer = typename OuterTraits::void_pointer; using const_void_pointer = typename OuterTraits::const_void_pointer; using propagate_on_container_copy_assignment = /* see description */; using propagate_on_container_move_assignment = /* see description */; using propagate_on_container_swap = /* see description */; using is_always_equal = /* see description */; template<class Tp> struct rebind { using other = scoped_allocator_adaptor< OuterTraits::template rebind_alloc<Tp>, InnerAllocs...>; }; scoped_allocator_adaptor(); template<class OuterA2> scoped_allocator_adaptor(OuterA2&& outerAlloc, const InnerAllocs&... innerAllocs) noexcept; scoped_allocator_adaptor(const scoped_allocator_adaptor& other) noexcept; scoped_allocator_adaptor(scoped_allocator_adaptor&& other) noexcept; template<class OuterA2> scoped_allocator_adaptor( const scoped_allocator_adaptor<OuterA2, InnerAllocs...>& other) noexcept; template<class OuterA2> scoped_allocator_adaptor( scoped_allocator_adaptor<OuterA2, InnerAllocs...>&& other) noexcept; scoped_allocator_adaptor& operator=(const scoped_allocator_adaptor&) = default; scoped_allocator_adaptor& operator=(scoped_allocator_adaptor&&) = default; ~scoped_allocator_adaptor(); inner_allocator_type& inner_allocator() noexcept; const inner_allocator_type& inner_allocator() const noexcept; outer_allocator_type& outer_allocator() noexcept; const outer_allocator_type& outer_allocator() const noexcept; [[nodiscard]] pointer allocate(size_type n); [[nodiscard]] pointer allocate(size_type n, const_void_pointer hint); void deallocate(pointer p, size_type n); size_type max_size() const; template<class T, class... Args> void construct(T* p, Args&&... args); template<class T> void destroy(T* p); scoped_allocator_adaptor select_on_container_copy_construction() const; }; template<class OuterAlloc, class... InnerAllocs> scoped_allocator_adaptor(OuterAlloc, InnerAllocs...) -> scoped_allocator_adaptor<OuterAlloc, InnerAllocs...>; } ``` cpp Standard library header <strstream> (deprecated in C++98) Standard library header <strstream> (deprecated in C++98) ========================================================= This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Classes | | [strstreambuf](../io/strstreambuf "cpp/io/strstreambuf") (deprecated in C++98) | implements raw character array device (class) | | [istrstream](../io/istrstream "cpp/io/istrstream") (deprecated in C++98) | implements character array input operations (class) | | [ostrstream](../io/ostrstream "cpp/io/ostrstream") (deprecated in C++98) | implements character array output operations (class) | | [strstream](../io/strstream "cpp/io/strstream") (deprecated in C++98) | implements character array input/output operations (class) | ### Synopsis ``` namespace std { class strstreambuf; class istrstream; class ostrstream; class strstream; } ``` #### Class `[std::strstreambuf](../io/strstreambuf "cpp/io/strstreambuf")` ``` namespace std { class strstreambuf : public basic_streambuf<char> { public: strstreambuf() : strstreambuf(0) {} explicit strstreambuf(streamsize alsize_arg); strstreambuf(void* (*palloc_arg)(size_t), void (*pfree_arg)(void*)); strstreambuf(char* gnext_arg, streamsize n, char* pbeg_arg = nullptr); strstreambuf(const char* gnext_arg, streamsize n); strstreambuf(signed char* gnext_arg, streamsize n, signed char* pbeg_arg = nullptr); strstreambuf(const signed char* gnext_arg, streamsize n); strstreambuf(unsigned char* gnext_arg, streamsize n, unsigned char* pbeg_arg = nullptr); strstreambuf(const unsigned char* gnext_arg, streamsize n); virtual ~strstreambuf(); void freeze(bool freezefl = true); char* str(); int pcount(); protected: int_type overflow (int_type c = EOF) override; int_type pbackfail(int_type c = EOF) override; int_type underflow() override; pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out) override; pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out) override; streambuf* setbuf(char* s, streamsize n) override; private: using strstate = /*bitmask type*/; // exposition only static const strstate allocated; // exposition only static const strstate constant; // exposition only static const strstate dynamic; // exposition only static const strstate frozen; // exposition only strstate strmode; // exposition only streamsize alsize; // exposition only void* (*palloc)(size_t); // exposition only void (*pfree)(void*); // exposition only }; } ``` #### Class `[std::istrstream](../io/istrstream "cpp/io/istrstream")` ``` namespace std { class istrstream : public basic_istream<char> { public: explicit istrstream(const char* s); explicit istrstream(char* s); istrstream(const char* s, streamsize n); istrstream(char* s, streamsize n); virtual ~istrstream(); strstreambuf* rdbuf() const; char* str(); private: strstreambuf sb; // exposition only }; } ``` #### Class `[std::ostrstream](../io/ostrstream "cpp/io/ostrstream")` ``` namespace std { class ostrstream : public basic_ostream<char> { public: ostrstream(); ostrstream(char* s, int n, ios_base::openmode mode = ios_base::out); virtual ~ostrstream(); strstreambuf* rdbuf() const; void freeze(bool freezefl = true); char* str(); int pcount() const; private: strstreambuf sb; // exposition only }; } ``` #### Class `[std::strstream](../io/strstream "cpp/io/strstream")` ``` namespace std { class strstream : public basic_iostream<char> { public: // types using char_type = char; using int_type = char_traits<char>::int_type; using pos_type = char_traits<char>::pos_type; using off_type = char_traits<char>::off_type; // constructors/destructor strstream(); strstream(char* s, int n, ios_base::openmode mode = ios_base::in | ios_base::out); virtual ~strstream(); // members strstreambuf* rdbuf() const; void freeze(bool freezefl = true); int pcount() const; char* str(); private: strstreambuf sb; // exposition only }; } ``` cpp Standard library header <cstdint> (C++11) Standard library header <cstdint> (C++11) ========================================= This header was originally in the C standard library as `<stdint.h>`. This header is part of the [type support](../types "cpp/types") library, providing [fixed width integer types](../types/integer "cpp/types/integer") and part of [C numeric limits interface](../types/climits "cpp/types/climits"). | | | --- | | Types | | int8\_tint16\_tint32\_tint64\_t (optional) | signed integer type with width of exactly 8, 16, 32 and 64 bits respectivelywith no padding bits and using 2's complement for negative values(provided if and only if the implementation directly supports the type) (typedef) | | int\_fast8\_tint\_fast16\_tint\_fast32\_tint\_fast64\_t | fastest signed integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) | | int\_least8\_tint\_least16\_tint\_least32\_tint\_least64\_t | smallest signed integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) | | intmax\_t | maximum-width signed integer type (typedef) | | intptr\_t (optional) | signed integer type capable of holding a pointer to `void` (typedef) | | uint8\_tuint16\_tuint32\_tuint64\_t (optional) | unsigned integer type with width of exactly 8, 16, 32 and 64 bits respectively (provided if and only if the implementation directly supports the type) (typedef) | | uint\_fast8\_tuint\_fast16\_tuint\_fast32\_tuint\_fast64\_t | fastest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) | | uint\_least8\_tuint\_least16\_tuint\_least32\_tuint\_least64\_t | smallest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef) | | uintmax\_t | maximum-width unsigned integer type (typedef) | | uintptr\_t (optional) | unsigned integer type capable of holding a pointer to `void` (typedef) | | Macros | | Signed integers : minimum value | | INT8\_MININT16\_MININT32\_MININT64\_MIN (optional) | minimum value of an object of type `int8_t`, `int16_t`, `int32_t`, `int64_t` (macro constant) | | INT\_FAST8\_MININT\_FAST16\_MININT\_FAST32\_MININT\_FAST64\_MIN | minimum value of an object of type `int_fast8_t`, `int_fast16_t`, `int_fast32_t`, `int_fast64_t` (macro constant) | | INT\_LEAST8\_MININT\_LEAST16\_MININT\_LEAST32\_MININT\_LEAST64\_MIN | minimum value of an object of type `int_least8_t`, `int_least16_t`, `int_least32_t`, `int_least64_t` (macro constant) | | INTPTR\_MIN (optional) | minimum value of an object of type `intptr_t` (macro constant) | | INTMAX\_MIN | minimum value of an object of type `intmax_t` (macro constant) | | Signed integers : maximum value | | INT8\_MAXINT16\_MAXINT32\_MAXINT64\_MAX (optional) | maximum value of an object of type `int8_t`, `int16_t`, `int32_t`, `int64_t` (macro constant) | | INT\_FAST8\_MAXINT\_FAST16\_MAXINT\_FAST32\_MAXINT\_FAST64\_MAX | maximum value of an object of type `int_fast8_t`, `int_fast16_t`, `int_fast32_t`, `int_fast64_t` (macro constant) | | INT\_LEAST8\_MAXINT\_LEAST16\_MAXINT\_LEAST32\_MAXINT\_LEAST64\_MAX | maximum value of an object of type `int_least8_t`, `int_least16_t`, `int_least32_t`, `int_least64_t` (macro constant) | | INTPTR\_MAX (optional) | maximum value of an object of type `intptr_t` (macro constant) | | INTMAX\_MAX | maximum value of an object of type `intmax_t` (macro constant) | | Unsigned integers : maximum value | | UINT8\_MAXUINT16\_MAXUINT32\_MAXUINT64\_MAX (optional) | maximum value of an object of type `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t` (macro constant) | | UINT\_FAST8\_MAXUINT\_FAST16\_MAXUINT\_FAST32\_MAXUINT\_FAST64\_MAX | maximum value of an object of type `uint_fast8_t`, `uint_fast16_t`, `uint_fast32_t`, `uint_fast64_t` (macro constant) | | UINT\_LEAST8\_MAXUINT\_LEAST16\_MAXUINT\_LEAST32\_MAXUINT\_LEAST64\_MAX | maximum value of an object of type `uint_least8_t`, `uint_least16_t`, `uint_least32_t`, `uint_least64_t` (macro constant) | | UINTPTR\_MAX (optional) | maximum value of an object of type `uintptr_t` (macro constant) | | UINTMAX\_MAX | maximum value of an object of type `uintmax_t` (macro constant) | | Limits of other integer types | | PTRDIFF\_MIN (C++11) | minimum value of object of `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` type (macro constant) | | PTRDIFF\_MAX (C++11) | maximum value of object of `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` type (macro constant) | | SIZE\_MAX (C++11) | maximum value of object of `[std::size\_t](../types/size_t "cpp/types/size t")` type (macro constant) | | SIG\_ATOMIC\_MIN (C++11) | minimum value of object of `[std::sig\_atomic\_t](../utility/program/sig_atomic_t "cpp/utility/program/sig atomic t")` type (macro constant) | | SIG\_ATOMIC\_MAX (C++11) | maximum value of object of `[std::sig\_atomic\_t](../utility/program/sig_atomic_t "cpp/utility/program/sig atomic t")` type (macro constant) | | WCHAR\_MIN (C++11) | minimum value of object of `wchar_t` type (macro constant) | | WCHAR\_MAX (C++11) | maximum value of object of `wchar_t` type (macro constant) | | WINT\_MIN (C++11) | minimum value of object of `std::wint_t` type (macro constant) | | WINT\_MAX (C++11) | maximum value of object of `std::wint_t` type (macro constant) | | Function macros for integer constants | | INT8\_CINT16\_CINT32\_CINT64\_C | expands to an integer constant expression having the value specified by its argument and whose type is the [promoted](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") type of `int_least8_t`, `int_least16_t`, `int_least32_t`, `int_least64_t` respectively (function macro) | | INTMAX\_C | expands to an integer constant expression having the value specified by its argument and the type `intmax_t` (function macro) | | UINT8\_CUINT16\_CUINT32\_CUINT64\_C | expands to an integer constant expression having the value specified by its argument and whose type is the [promoted](../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion") type of `uint_least8_t`, `uint_least16_t`, `uint_least32_t`, `uint_least64_t` respectively (function macro) | | UINTMAX\_C | expands to an integer constant expression having the value specified by its argument and the type `uintmax_t` (function macro) | ### Synopsis ``` namespace std { using int8_t = /* signed integer type */; // optional using int16_t = /* signed integer type */; // optional using int32_t = /* signed integer type */; // optional using int64_t = /* signed integer type */; // optional using intN_t = /* see description */; // optional, see description using int_fast8_t = /* signed integer type */; using int_fast16_t = /* signed integer type */; using int_fast32_t = /* signed integer type */; using int_fast64_t = /* signed integer type */; using int_fastN_t = /* see description */; // optional, see description using int_least8_t = /* signed integer type */; using int_least16_t = /* signed integer type */; using int_least32_t = /* signed integer type */; using int_least64_t = /* signed integer type */; using int_leastN_t = /* see description */; // optional, see description using intmax_t = /* signed integer type */; using intptr_t = /* signed integer type */; // optional using uint8_t = /* unsigned integer type */; // optional using uint16_t = /* unsigned integer type */; // optional using uint32_t = /* unsigned integer type */; // optional using uint64_t = /* unsigned integer type */; // optional using uintN_t = /* see description */; // optional, see description using uint_fast8_t = /* unsigned integer type */; using uint_fast16_t = /* unsigned integer type */; using uint_fast32_t = /* unsigned integer type */; using uint_fast64_t = /* unsigned integer type */; using uint_fastN_t = /* see description */; // optional, see description using uint_least8_t = /* unsigned integer type */; using uint_least16_t = /* unsigned integer type */; using uint_least32_t = /* unsigned integer type */; using uint_least64_t = /* unsigned integer type */; using uint_leastN_t = /* see description */; // optional, see description using uintmax_t = /* unsigned integer type */; using uintptr_t = /* unsigned integer type */; // optional } #define INTN_MIN /* see description */ #define INTN_MAX /* see description */ #define UINTN_MAX /* see description */ #define INT_FASTN_MIN /* see description */ #define INT_FASTN_MAX /* see description */ #define UINT_FASTN_MAX /* see description */ #define INT_LEASTN_MIN /* see description */ #define INT_LEASTN_MAX /* see description */ #define UINT_LEASTN_MAX /* see description */ #define INTMAX_MIN /* see description */ #define INTMAX_MAX /* see description */ #define UINTMAX_MAX /* see description */ #define INTPTR_MIN /* see description */ // optional #define INTPTR_MAX /* see description */ // optional #define UINTPTR_MAX /* see description */ // optional #define PTRDIFF_MIN /* see description */ #define PTRDIFF_MAX /* see description */ #define SIZE_MAX /* see description */ #define SIG_ATOMIC_MIN /* see description */ #define SIG_ATOMIC_MAX /* see description */ #define WCHAR_MIN /* see description */ #define WCHAR_MAX /* see description */ #define WINT_MIN /* see description */ #define WINT_MAX /* see description */ #define INTN_C(value) /* see description */ #define UINTN_C(value) /* see description */ #define INTMAX_C(value) /* see description */ #define UINTMAX_C(value) /* see description */ ``` cpp Standard library header <ctime> Standard library header <ctime> =============================== This header was originally in the C standard library as `<time.h>`. This header is part of the [C-style date and time](../chrono/c "cpp/chrono/c") library. | | | --- | | Macro constants | | [CLOCKS\_PER\_SEC](../chrono/c/clocks_per_sec "cpp/chrono/c/CLOCKS PER SEC") | number of processor clock ticks per second (macro constant) | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | Types | | [clock\_t](../chrono/c/clock_t "cpp/chrono/c/clock t") | process running time (typedef) | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | | [time\_t](../chrono/c/time_t "cpp/chrono/c/time t") | time since epoch type (typedef) | | [tm](../chrono/c/tm "cpp/chrono/c/tm") | calendar time type (class) | | [timespec](../chrono/c/timespec "cpp/chrono/c/timespec") (C++17) | time in seconds and nanoseconds (struct) | | Functions | | Time manipulation | | [clock](../chrono/c/clock "cpp/chrono/c/clock") | returns raw processor clock time since the program is started (function) | | [time](../chrono/c/time "cpp/chrono/c/time") | returns the current time of the system as time since epoch (function) | | [difftime](../chrono/c/difftime "cpp/chrono/c/difftime") | computes the difference between times (function) | | [timespec\_get](../chrono/c/timespec_get "cpp/chrono/c/timespec get") (C++17) | returns the calendar time in seconds and nanoseconds based on a given time base (function) | | Format conversions | | [ctime](../chrono/c/ctime "cpp/chrono/c/ctime") | converts a `[std::time\_t](../chrono/c/time_t "cpp/chrono/c/time t")` object to a textual representation (function) | | [asctime](../chrono/c/asctime "cpp/chrono/c/asctime") | converts a `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` object to a textual representation (function) | | [strftime](../chrono/c/strftime "cpp/chrono/c/strftime") | converts a `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` object to custom textual representation (function) | | [wcsftime](../chrono/c/wcsftime "cpp/chrono/c/wcsftime") | converts a `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` object to custom wide string textual representation (function) | | [gmtime](../chrono/c/gmtime "cpp/chrono/c/gmtime") | converts time since epoch to calendar time expressed as Universal Coordinated Time (function) | | [localtime](../chrono/c/localtime "cpp/chrono/c/localtime") | converts time since epoch to calendar time expressed as local time (function) | | [mktime](../chrono/c/mktime "cpp/chrono/c/mktime") | converts calendar time to time since epoch (function) | ### Synopsis ``` #define NULL /* see description */ #define CLOCKS_PER_SEC /* see description */ #define TIME_UTC /* see description */ namespace std { using size_t = /* see description */; using clock_t = /* see description */; using time_t = /* see description */; struct timespec; struct tm; clock_t clock(); double difftime(time_t time1, time_t time0); time_t mktime(tm* timeptr); time_t time(time_t* timer); int timespec_get(timespec* ts, int base); char* asctime(const tm* timeptr); char* ctime(const time_t* timer); tm* gmtime(const time_t* timer); tm* localtime(const time_t* timer); size_t strftime(char* s, size_t maxsize, const char* format, const tm* timeptr); } ``` ### Class `[std::timespec](../chrono/c/timespec "cpp/chrono/c/timespec")` ``` struct timespec { std::time_t tv_sec; long tv_nsec; }; ``` ### Class `[std::tm](../chrono/c/tm "cpp/chrono/c/tm")` ``` struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; ```
programming_docs
cpp Standard library header <cstring> Standard library header <cstring> ================================= This header was originally in the C standard library as `<string.h>`. This header is for [C-style null-terminated byte strings](../string/byte "cpp/string/byte"). ### Macros | | | | --- | --- | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | ### Types | | | | --- | --- | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | ### Functions | | | --- | | String manipulation | | [strcpy](../string/byte/strcpy "cpp/string/byte/strcpy") | copies one string to another (function) | | [strncpy](../string/byte/strncpy "cpp/string/byte/strncpy") | copies a certain amount of characters from one string to another (function) | | [strcat](../string/byte/strcat "cpp/string/byte/strcat") | concatenates two strings (function) | | [strncat](../string/byte/strncat "cpp/string/byte/strncat") | concatenates a certain amount of characters of two strings (function) | | [strxfrm](../string/byte/strxfrm "cpp/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) | | String examination | | [strlen](../string/byte/strlen "cpp/string/byte/strlen") | returns the length of a given string (function) | | [strcmp](../string/byte/strcmp "cpp/string/byte/strcmp") | compares two strings (function) | | [strncmp](../string/byte/strncmp "cpp/string/byte/strncmp") | compares a certain number of characters from two strings (function) | | [strcoll](../string/byte/strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) | | [strchr](../string/byte/strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) | | [strrchr](../string/byte/strrchr "cpp/string/byte/strrchr") | finds the last occurrence of a character (function) | | [strspn](../string/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](../string/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](../string/byte/strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) | | [strstr](../string/byte/strstr "cpp/string/byte/strstr") | finds the first occurrence of a substring of characters (function) | | [strtok](../string/byte/strtok "cpp/string/byte/strtok") | finds the next token in a byte string (function) | | Character array manipulation | | [memchr](../string/byte/memchr "cpp/string/byte/memchr") | searches an array for the first occurrence of a character (function) | | [memcmp](../string/byte/memcmp "cpp/string/byte/memcmp") | compares two buffers (function) | | [memset](../string/byte/memset "cpp/string/byte/memset") | fills a buffer with a character (function) | | [memcpy](../string/byte/memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) | | [memmove](../string/byte/memmove "cpp/string/byte/memmove") | moves one buffer to another (function) | | Miscellaneous | | [strerror](../string/byte/strerror "cpp/string/byte/strerror") | returns a text version of a given error code (function) | ### Notes * `[NULL](../types/null "cpp/types/NULL")` is also defined in the following headers: + [`<clocale>`](clocale "cpp/header/clocale") + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<cstdio>`](cstdio "cpp/header/cstdio") + [`<cwchar>`](cwchar "cpp/header/cwchar") * `[std::size\_t](../types/size_t "cpp/types/size t")` is also defined in the following headers: + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<cstdio>`](cstdio "cpp/header/cstdio") + [`<cuchar>`](cuchar "cpp/header/cuchar") (since C++17) + [`<cwchar>`](cwchar "cpp/header/cwchar") cpp Standard library header <sstream> Standard library header <sstream> ================================= This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Classes | | [basic\_stringbuf](../io/basic_stringbuf "cpp/io/basic stringbuf") | implements raw string device (class template) | | [basic\_istringstream](../io/basic_istringstream "cpp/io/basic istringstream") | implements high-level string stream input operations (class template) | | [basic\_ostringstream](../io/basic_ostringstream "cpp/io/basic ostringstream") | implements high-level string stream output operations (class template) | | [basic\_stringstream](../io/basic_stringstream "cpp/io/basic stringstream") | implements high-level string stream input/output operations (class template) | | `stringbuf` | `[std::basic\_stringbuf](http://en.cppreference.com/w/cpp/io/basic_stringbuf)<char>`(typedef) | | `wstringbuf` | `[std::basic\_stringbuf](http://en.cppreference.com/w/cpp/io/basic_stringbuf)<wchar\_t>`(typedef) | | `istringstream` | `[std::basic\_istringstream](http://en.cppreference.com/w/cpp/io/basic_istringstream)<char>`(typedef) | | `wistringstream` | `[std::basic\_istringstream](http://en.cppreference.com/w/cpp/io/basic_istringstream)<wchar\_t>`(typedef) | | `ostringstream` | `[std::basic\_ostringstream](http://en.cppreference.com/w/cpp/io/basic_ostringstream)<char>`(typedef) | | `wostringstream` | `[std::basic\_ostringstream](http://en.cppreference.com/w/cpp/io/basic_ostringstream)<wchar\_t>`(typedef) | | `stringstream` | `[std::basic\_stringstream](http://en.cppreference.com/w/cpp/io/basic_stringstream)<char>`(typedef) | | `wstringstream` | `[std::basic\_stringstream](http://en.cppreference.com/w/cpp/io/basic_stringstream)<wchar\_t>`(typedef) | | Functions | | [std::swap(std::basic\_stringbuf)](../io/basic_stringbuf/swap2 "cpp/io/basic stringbuf/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_istringstream)](../io/basic_istringstream/swap2 "cpp/io/basic istringstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_ostringstream)](../io/basic_ostringstream/swap2 "cpp/io/basic ostringstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_stringstream)](../io/basic_stringstream/swap2 "cpp/io/basic stringstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_stringbuf; using stringbuf = basic_stringbuf<char>; using wstringbuf = basic_stringbuf<wchar_t>; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_istringstream; using istringstream = basic_istringstream<char>; using wistringstream = basic_istringstream<wchar_t>; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_ostringstream; using ostringstream = basic_ostringstream<char>; using wostringstream = basic_ostringstream<wchar_t>; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_stringstream; using stringstream = basic_stringstream<char>; using wstringstream = basic_stringstream<wchar_t>; } ``` #### Class template `[std::basic\_stringbuf](../io/basic_stringbuf "cpp/io/basic stringbuf")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_stringbuf : public basic_streambuf<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using Traits_type = Traits; using allocator_type = Allocator; // constructors basic_stringbuf() : basic_stringbuf(ios_base::in | ios_base::out) {} explicit basic_stringbuf(ios_base::openmode which); explicit basic_stringbuf( const basic_string<CharT, Traits, Allocator>& s, ios_base::openmode which = ios_base::in | ios_base::out); explicit basic_stringbuf(const Allocator& a) : basic_stringbuf(ios_base::in | ios_base::out, a) {} basic_stringbuf(ios_base::openmode which, const Allocator& a); explicit basic_stringbuf( basic_string<CharT, Traits, Allocator>&& s, ios_base::openmode which = ios_base::in | ios_base::out); template<class SAlloc> basic_stringbuf( const basic_string<CharT, Traits, SAlloc>& s, const Allocator& a) : basic_stringbuf(s, ios_base::in | ios_base::out, a) {} template<class SAlloc> basic_stringbuf( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which, const Allocator& a); template<class SAlloc> explicit basic_stringbuf( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which = ios_base::in | ios_base::out); basic_stringbuf(const basic_stringbuf&) = delete; basic_stringbuf(basic_stringbuf&& rhs); basic_stringbuf(basic_stringbuf&& rhs, const Allocator& a); // assign and swap basic_stringbuf& operator=(const basic_stringbuf&) = delete; basic_stringbuf& operator=(basic_stringbuf&& rhs); void swap(basic_stringbuf& rhs) noexcept(see below); // getters and setters allocator_type get_allocator() const noexcept; basic_string<CharT, Traits, Allocator> str() const &; template<class SAlloc> basic_string<CharT,Traits,SAlloc> str(const SAlloc& sa) const; basic_string<CharT, Traits, Allocator> str() &&; basic_string_view<CharT, Traits> view() const noexcept; void str(const basic_string<CharT, Traits, Allocator>& s); template<class SAlloc> void str(const basic_string<CharT, Traits, SAlloc>& s); void str(basic_string<CharT, Traits, Allocator>&& s); protected: // overridden virtual functions int_type underflow() override; int_type pbackfail(int_type c = Traits::eof()) override; int_type overflow (int_type c = Traits::eof()) override; basic_streambuf<CharT, Traits>* setbuf(CharT*, streamsize) override; pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out) override; pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out) override; private: ios_base::openmode mode; // exposition only basic_string<CharT, Traits, Allocator> buf; // exposition only void init_buf_ptrs(); // exposition only }; template<class CharT, class Traits, class Allocator> void swap(basic_stringbuf<CharT, Traits, Allocator>& x, basic_stringbuf<CharT, Traits, Allocator>& y) noexcept(noexcept(x.swap(y))); } ``` #### Class template `[std::basic\_istringstream](../io/basic_istringstream "cpp/io/basic istringstream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_istringstream : public basic_istream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using Traits_type = Traits; using allocator_type = Allocator; // constructors basic_istringstream() : basic_istringstream(ios_base::in) {} explicit basic_istringstream(ios_base::openmode which); explicit basic_istringstream( const basic_string<CharT, Traits, Allocator>& s, ios_base::openmode which = ios_base::in); basic_istringstream(ios_base::openmode which, const Allocator& a); explicit basic_istringstream( basic_string<CharT, Traits, Allocator>&& s, ios_base::openmode which = ios_base::in); template<class SAlloc> basic_istringstream( const basic_string<CharT, Traits, SAlloc>& s, const Allocator& a) : basic_istringstream(s, ios_base::in, a) {} template<class SAlloc> basic_istringstream( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which, const Allocator& a); template<class SAlloc> explicit basic_istringstream( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which = ios_base::in); basic_istringstream(const basic_istringstream&) = delete; basic_istringstream(basic_istringstream&& rhs); // assign and swap basic_istringstream& operator=(const basic_istringstream&) = delete; basic_istringstream& operator=(basic_istringstream&& rhs); void swap(basic_istringstream& rhs); // members basic_stringbuf<CharT, Traits, Allocator>* rdbuf() const; basic_string<CharT, Traits, Allocator> str() const &; template<class SAlloc> basic_string<CharT,Traits,SAlloc> str(const SAlloc& sa) const; basic_string<CharT, Traits, Allocator> str() &&; basic_string_view<CharT, Traits> view() const noexcept; void str(const basic_string<CharT, Traits, Allocator>& s); template<class SAlloc> void str(const basic_string<CharT, Traits, SAlloc>& s); void str(basic_string<CharT, Traits, Allocator>&& s); private: basic_stringbuf<CharT, Traits, Allocator> sb; // exposition only }; template<class CharT, class Traits, class Allocator> void swap(basic_istringstream<CharT, Traits, Allocator>& x, basic_istringstream<CharT, Traits, Allocator>& y); } ``` #### Class template `[std::basic\_ostringstream](../io/basic_ostringstream "cpp/io/basic ostringstream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_ostringstream : public basic_ostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using Traits_type = Traits; using allocator_type = Allocator; // constructors basic_ostringstream() : basic_ostringstream(ios_base::out) {} explicit basic_ostringstream(ios_base::openmode which); explicit basic_ostringstream( const basic_string<CharT, Traits, Allocator>& s, ios_base::openmode which = ios_base::out); basic_ostringstream(ios_base::openmode which, const Allocator& a); explicit basic_ostringstream( basic_string<CharT, Traits, Allocator>&& s, ios_base::openmode which = ios_base::out); template<class SAlloc> basic_ostringstream( const basic_string<CharT, Traits, SAlloc>& s, const Allocator& a) : basic_ostringstream(s, ios_base::out, a) {} template<class SAlloc> basic_ostringstream( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which, const Allocator& a); template<class SAlloc> explicit basic_ostringstream( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which = ios_base::out); basic_ostringstream(const basic_ostringstream&) = delete; basic_ostringstream(basic_ostringstream&& rhs); // assign and swap basic_ostringstream& operator=(const basic_ostringstream&) = delete; basic_ostringstream& operator=(basic_ostringstream&& rhs); void swap(basic_ostringstream& rhs); // members basic_stringbuf<CharT, Traits, Allocator>* rdbuf() const; basic_string<CharT, Traits, Allocator> str() const &; template<class SAlloc> basic_string<CharT,Traits,SAlloc> str(const SAlloc& sa) const; basic_string<CharT, Traits, Allocator> str() &&; basic_string_view<CharT, Traits> view() const noexcept; void str(const basic_string<CharT, Traits, Allocator>& s); template<class SAlloc> void str(const basic_string<CharT, Traits, SAlloc>& s); void str(basic_string<CharT, Traits, Allocator>&& s); private: basic_stringbuf<CharT, Traits, Allocator> sb; // exposition only }; template<class CharT, class Traits, class Allocator> void swap(basic_ostringstream<CharT, Traits, Allocator>& x, basic_ostringstream<CharT, Traits, Allocator>& y); } ``` #### Class template `[std::basic\_stringstream](../io/basic_stringstream "cpp/io/basic stringstream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_stringstream : public basic_iostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using Traits_type = Traits; using allocator_type = Allocator; // constructors basic_stringstream() : basic_stringstream(ios_base::out | ios_base::in) {} explicit basic_stringstream(ios_base::openmode which); explicit basic_stringstream( const basic_string<CharT, Traits, Allocator>& s, ios_base::openmode which = ios_base::out | ios_base::in); basic_stringstream(ios_base::openmode which, const Allocator& a); explicit basic_stringstream( basic_string<CharT, Traits, Allocator>&& s, ios_base::openmode which = ios_base::out | ios_base::in); template<class SAlloc> basic_stringstream( const basic_string<CharT, Traits, SAlloc>& s, const Allocator& a) : basic_stringstream(s, ios_base::out | ios_base::in, a) {} template<class SAlloc> basic_stringstream( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which, const Allocator& a); template<class SAlloc> explicit basic_stringstream( const basic_string<CharT, Traits, SAlloc>& s, ios_base::openmode which = ios_base::out | ios_base::in); basic_stringstream(const basic_stringstream&) = delete; basic_stringstream(basic_stringstream&& rhs); // assign and swap basic_stringstream& operator=(const basic_stringstream&) = delete; basic_stringstream& operator=(basic_stringstream&& rhs); void swap(basic_stringstream& rhs); // members basic_stringbuf<CharT, Traits, Allocator>* rdbuf() const; basic_string<CharT, Traits, Allocator> str() const &; template<class SAlloc> basic_string<CharT,Traits,SAlloc> str(const SAlloc& sa) const; basic_string<CharT, Traits, Allocator> str() &&; basic_string_view<CharT, Traits> view() const noexcept; void str(const basic_string<CharT, Traits, Allocator>& s); template<class SAlloc> void str(const basic_string<CharT, Traits, SAlloc>& s); void str(basic_string<CharT, Traits, Allocator>&& s); private: basic_stringbuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits, class Allocator> void swap(basic_stringstream<CharT, Traits, Allocator>& x, basic_stringstream<CharT, Traits, Allocator>& y); } ``` cpp Standard library header <cctype> Standard library header <cctype> ================================ This header was originally in the C standard library as `<ctype.h>`. This header is part of the [null-terminated byte strings](../string/byte "cpp/string/byte") library. | | | --- | | Functions | | [isalnum](../string/byte/isalnum "cpp/string/byte/isalnum") | checks if a character is alphanumeric (function) | | [isalpha](../string/byte/isalpha "cpp/string/byte/isalpha") | checks if a character is alphabetic (function) | | [islower](../string/byte/islower "cpp/string/byte/islower") | checks if a character is lowercase (function) | | [isupper](../string/byte/isupper "cpp/string/byte/isupper") | checks if a character is an uppercase character (function) | | [isdigit](../string/byte/isdigit "cpp/string/byte/isdigit") | checks if a character is a digit (function) | | [isxdigit](../string/byte/isxdigit "cpp/string/byte/isxdigit") | checks if a character is a hexadecimal character (function) | | [iscntrl](../string/byte/iscntrl "cpp/string/byte/iscntrl") | checks if a character is a control character (function) | | [isgraph](../string/byte/isgraph "cpp/string/byte/isgraph") | checks if a character is a graphical character (function) | | [isspace](../string/byte/isspace "cpp/string/byte/isspace") | checks if a character is a space character (function) | | [isblank](../string/byte/isblank "cpp/string/byte/isblank") (C++11) | checks if a character is a blank character (function) | | [isprint](../string/byte/isprint "cpp/string/byte/isprint") | checks if a character is a printing character (function) | | [ispunct](../string/byte/ispunct "cpp/string/byte/ispunct") | checks if a character is a punctuation character (function) | | [tolower](../string/byte/tolower "cpp/string/byte/tolower") | converts a character to lowercase (function) | | [toupper](../string/byte/toupper "cpp/string/byte/toupper") | converts a character to uppercase (function) | ### Synopsis ``` namespace std { int isalnum(int c); int isalpha(int c); int isblank(int c); int iscntrl(int c); int isdigit(int c); int isgraph(int c); int islower(int c); int isprint(int c); int ispunct(int c); int isspace(int c); int isupper(int c); int isxdigit(int c); int tolower(int c); int toupper(int c); } ```
programming_docs
cpp Standard library header <queue> Standard library header <queue> =============================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [queue](../container/queue "cpp/container/queue") | adapts a container to provide queue (FIFO data structure) (class template) | | [priority\_queue](../container/priority_queue "cpp/container/priority queue") | adapts a container to provide priority queue (class template) | | [std::uses\_allocator<std::queue>](../container/queue/uses_allocator "cpp/container/queue/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | [std::uses\_allocator<std::priority\_queue>](../container/priority_queue/uses_allocator "cpp/container/priority queue/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/queue/operator_cmp "cpp/container/queue/operator cmp") (C++20) | lexicographically compares the values in the queue (function template) | | [std::swap(std::queue)](../container/queue/swap2 "cpp/container/queue/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::priority\_queue)](../container/priority_queue/swap2 "cpp/container/priority queue/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { template<class T, class Container = deque<T>> class queue; template<class T, class Container> bool operator==(const queue<T, Container>& x, const queue<T, Container>& y); template<class T, class Container> bool operator!=(const queue<T, Container>& x, const queue<T, Container>& y); template<class T, class Container> bool operator< (const queue<T, Container>& x, const queue<T, Container>& y); template<class T, class Container> bool operator> (const queue<T, Container>& x, const queue<T, Container>& y); template<class T, class Container> bool operator<=(const queue<T, Container>& x, const queue<T, Container>& y); template<class T, class Container> bool operator>=(const queue<T, Container>& x, const queue<T, Container>& y); template<class T, three_way_comparable Container> compare_three_way_result_t<Container> operator<=>(const queue<T, Container>& x, const queue<T, Container>& y); template<class T, class Container> void swap(queue<T, Container>& x, queue<T, Container>& y) noexcept(noexcept(x.swap(y))); template<class T, class Container, class Alloc> struct uses_allocator<queue<T, Container>, Alloc>; template<class T, class Container = vector<T>, class Compare = less<typename Container::value_type>> class priority_queue; template<class T, class Container, class Compare> void swap(priority_queue<T, Container, Compare>& x, priority_queue<T, Container, Compare>& y) noexcept(noexcept(x.swap(y))); template<class T, class Container, class Compare, class Alloc> struct uses_allocator<priority_queue<T, Container, Compare>, Alloc>; } ``` #### Class template `[std::queue](../container/queue "cpp/container/queue")` ``` namespace std { template<class T, class Container = deque<T>> class queue { public: using value_type = typename Container::value_type; using reference = typename Container::reference; using const_reference = typename Container::const_reference; using size_type = typename Container::size_type; using container_type = Container; protected: Container c; public: queue() : queue(Container()) {} explicit queue(const Container&); explicit queue(Container&&); template<class InputIt> queue(InputIt first, InputIt last); template<class Alloc> explicit queue(const Alloc&); template<class Alloc> queue(const Container&, const Alloc&); template<class Alloc> queue(Container&&, const Alloc&); template<class Alloc> queue(const queue&, const Alloc&); template<class Alloc> queue(queue&&, const Alloc&); template<class InputIt, class Alloc> queue(InputIt first, InputIt last, const Alloc&); [[nodiscard]] bool empty() const { return c.empty(); } size_type size() const { return c.size(); } reference front() { return c.front(); } const_reference front() const { return c.front(); } reference back() { return c.back(); } const_reference back() const { return c.back(); } void push(const value_type& x) { c.push_back(x); } void push(value_type&& x) { c.push_back(std::move(x)); } template<class... Args> decltype(auto) emplace(Args&&... args) { return c.emplace_back(std::forward<Args>(args)...); } void pop() { c.pop_front(); } void swap(queue& q) noexcept(is_nothrow_swappable_v<Container>) { using std::swap; swap(c, q.c); } }; template<class Container> queue(Container) -> queue<typename Container::value_type, Container>; template<class InputIt> queue(InputIt, InputIt) -> queue</*iter-value-type*/<InputIt>>; template<class Container, class Allocator> queue(Container, Allocator) -> queue<typename Container::value_type, Container>; template<class InputIt, class Allocator> queue(InputIt, InputIt, Allocator) -> queue</*iter-value-type*/<InputIt>, deque</*iter-value-type*/<InputIt>, Allocator>>; template<class T, class Container, class Alloc> struct uses_allocator<queue<T, Container>, Alloc> : uses_allocator<Container, Alloc>::type { }; } ``` #### Class template `[std::priority\_queue](../container/priority_queue "cpp/container/priority queue")` ``` namespace std { template<class T, class Container = vector<T>, class Compare = less<typename Container::value_type>> class priority_queue { public: using value_type = typename Container::value_type; using reference = typename Container::reference; using const_reference = typename Container::const_reference; using size_type = typename Container::size_type; using container_type = Container; using value_compare = Compare; protected: Container c; Compare comp; public: priority_queue() : priority_queue(Compare()) {} explicit priority_queue(const Compare& x) : priority_queue(x, Container()) {} priority_queue(const Compare& x, const Container&); priority_queue(const Compare& x, Container&&); template<class InputIt> priority_queue(InputIt first, InputIt last, const Compare& x = Compare()); template<class InputIt> priority_queue(InputIt first, InputIt last, const Compare& x, const Container&); template<class InputIt> priority_queue(InputIt first, InputIt last, const Compare& x, Container&&); template<class Alloc> explicit priority_queue(const Alloc&); template<class Alloc> priority_queue(const Compare&, const Alloc&); template<class Alloc> priority_queue(const Compare&, const Container&, const Alloc&); template<class Alloc> priority_queue(const Compare&, Container&&, const Alloc&); template<class Alloc> priority_queue(const priority_queue&, const Alloc&); template<class Alloc> priority_queue(priority_queue&&, const Alloc&); template<class InputIt, class Alloc> priority_queue(InputIt, InputIt, const Alloc&); template<class InputIt, class Alloc> priority_queue(InputIt, InputIt, const Compare&, const Alloc&); template<class InputIt, class Alloc> priority_queue(InputIt, InputIt, const Compare&, const Container&, const Alloc&); template<class InputIt, class Alloc> priority_queue(InputIt, InputIt, const Compare&, Container&&, const Alloc&); [[nodiscard]] bool empty() const { return c.empty(); } size_type size() const { return c.size(); } const_reference top() const { return c.front(); } void push(const value_type& x); void push(value_type&& x); template<class... Args> void emplace(Args&&... args); void pop(); void swap(priority_queue& q) noexcept(is_nothrow_swappable_v<Container> && is_nothrow_swappable_v<Compare>) { using std::swap; swap(c, q.c); swap(comp, q.comp); } }; template<class Compare, class Container> priority_queue(Compare, Container) -> priority_queue<typename Container::value_type, Container, Compare>; template<class InputIt, class Compare = less</*iter-value-type*/<InputIt>>, class Container = vector</*iter-value-type*/<InputIt>>> priority_queue(InputIt, InputIt, Compare = Compare(), Container = Container()) -> priority_queue</*iter-value-type*/<InputIt>, Container, Compare>; template<class Compare, class Container, class Allocator> priority_queue(Compare, Container, Allocator) -> priority_queue<typename Container::value_type, Container, Compare>; template<class InputIt, class Allocator> priority_queue(InputIt, InputIt, Allocator) -> priority_queue</*iter-value-type*/<InputIt>, vector</*iter-value-type*/<InputIt>, Allocator>, less</*iter-value-type*/<InputIt>>>; template<class InputIt, class Compare, class Allocator> priority_queue(InputIt, InputIt, Compare, Allocator) -> priority_queue</*iter-value-type*/<InputIt>, vector</*iter-value-type*/<InputIt>, Allocator>, Compare>; template<class InputIt, class Compare, class Container, class Allocator> priority_queue(InputIt, InputIt, Compare, Container, Allocator) -> priority_queue<typename Container::value_type, Container, Compare>; // no equality is provided template<class T, class Container, class Compare, class Alloc> struct uses_allocator<priority_queue<T, Container, Compare>, Alloc> : uses_allocator<Container, Alloc>::type { }; } ``` cpp Standard library header <functional> Standard library header <functional> ==================================== This header is part of the [function objects](../utility/functional "cpp/utility/functional") library and provides the standard [hash function](../utility/hash "cpp/utility/hash"). | | | --- | | Namespaces | | [`placeholders`](../utility/functional/placeholders "cpp/utility/functional/placeholders") (C++11) | Provides placeholders for the unbound arguments in a `[std::bind](../utility/functional/bind "cpp/utility/functional/bind")` expression | | Classes | | Wrappers | | [function](../utility/functional/function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](../utility/functional/move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | | [mem\_fn](../utility/functional/mem_fn "cpp/utility/functional/mem fn") (C++11) | creates a function object out of a pointer to a member (function template) | | [reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper") (C++11) | [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") reference wrapper (class template) | | [unwrap\_referenceunwrap\_ref\_decay](../utility/functional/unwrap_reference "cpp/utility/functional/unwrap reference") (C++20)(C++20) | get the reference type wrapped in `[std::reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper")` (class template) | | Helper classes | | [bad\_function\_call](../utility/functional/bad_function_call "cpp/utility/functional/bad function call") (C++11) | the exception thrown when invoking an empty `[std::function](../utility/functional/function "cpp/utility/functional/function")` (class) | | [is\_bind\_expression](../utility/functional/is_bind_expression "cpp/utility/functional/is bind expression") (C++11) | indicates that an object is `std::bind` expression or can be used as one (class template) | | [is\_placeholder](../utility/functional/is_placeholder "cpp/utility/functional/is placeholder") (C++11) | indicates that an object is a standard placeholder or can be used as one (class template) | | Arithmetic operations | | [plus](../utility/functional/plus "cpp/utility/functional/plus") | function object implementing `x + y` (class template) | | [minus](../utility/functional/minus "cpp/utility/functional/minus") | function object implementing `x - y` (class template) | | [multiplies](../utility/functional/multiplies "cpp/utility/functional/multiplies") | function object implementing `x * y` (class template) | | [divides](../utility/functional/divides "cpp/utility/functional/divides") | function object implementing `x / y` (class template) | | [modulus](../utility/functional/modulus "cpp/utility/functional/modulus") | function object implementing `x % y` (class template) | | [negate](../utility/functional/negate "cpp/utility/functional/negate") | function object implementing `-x` (class template) | | Comparisons | | [equal\_to](../utility/functional/equal_to "cpp/utility/functional/equal to") | function object implementing `x == y` (class template) | | [not\_equal\_to](../utility/functional/not_equal_to "cpp/utility/functional/not equal to") | function object implementing `x != y` (class template) | | [greater](../utility/functional/greater "cpp/utility/functional/greater") | function object implementing `x > y` (class template) | | [less](../utility/functional/less "cpp/utility/functional/less") | function object implementing `x < y` (class template) | | [greater\_equal](../utility/functional/greater_equal "cpp/utility/functional/greater equal") | function object implementing `x >= y` (class template) | | [less\_equal](../utility/functional/less_equal "cpp/utility/functional/less equal") | function object implementing `x <= y` (class template) | | Concept-constrained comparisons | | [ranges::equal\_to](../utility/functional/ranges/equal_to "cpp/utility/functional/ranges/equal to") (C++20) | function object implementing `x == y` (class) | | [ranges::not\_equal\_to](../utility/functional/ranges/not_equal_to "cpp/utility/functional/ranges/not equal to") (C++20) | function object implementing `x != y` (class) | | [ranges::greater](../utility/functional/ranges/greater "cpp/utility/functional/ranges/greater") (C++20) | function object implementing `x > y` (class) | | [ranges::less](../utility/functional/ranges/less "cpp/utility/functional/ranges/less") (C++20) | function object implementing `x < y` (class) | | [ranges::greater\_equal](../utility/functional/ranges/greater_equal "cpp/utility/functional/ranges/greater equal") (C++20) | function object implementing `x >= y` (class) | | [ranges::less\_equal](../utility/functional/ranges/less_equal "cpp/utility/functional/ranges/less equal") (C++20) | function object implementing `x <= y` (class) | | [compare\_three\_way](../utility/compare/compare_three_way "cpp/utility/compare/compare three way") (C++20) | function object implementing `x <=> y` (class) | | Logical operations | | [logical\_and](../utility/functional/logical_and "cpp/utility/functional/logical and") | function object implementing `x && y` (class template) | | [logical\_or](../utility/functional/logical_or "cpp/utility/functional/logical or") | function object implementing `x || y` (class template) | | [logical\_not](../utility/functional/logical_not "cpp/utility/functional/logical not") | function object implementing `!x` (class template) | | Bitwise operations | | [bit\_and](../utility/functional/bit_and "cpp/utility/functional/bit and") | function object implementing `x & y` (class template) | | [bit\_or](../utility/functional/bit_or "cpp/utility/functional/bit or") | function object implementing `x | y` (class template) | | [bit\_xor](../utility/functional/bit_xor "cpp/utility/functional/bit xor") | function object implementing `x ^ y` (class template) | | [bit\_not](../utility/functional/bit_not "cpp/utility/functional/bit not") (C++14) | function object implementing `~x` (class template) | | Negators | | [not\_fn](../utility/functional/not_fn "cpp/utility/functional/not fn") (C++17) | Creates a function object that returns the complement of the result of the function object it holds (function template) | | Identities | | [identity](../utility/functional/identity "cpp/utility/functional/identity") (C++20) | function object that returns its argument unchanged (class) | | Searchers | | [default\_searcher](../utility/functional/default_searcher "cpp/utility/functional/default searcher") (C++17) | standard C++ library search algorithm implementation (class template) | | [boyer\_moore\_searcher](../utility/functional/boyer_moore_searcher "cpp/utility/functional/boyer moore searcher") (C++17) | Boyer-Moore search algorithm implementation (class template) | | [boyer\_moore\_horspool\_searcher](../utility/functional/boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher") (C++17) | Boyer-Moore-Horspool search algorithm implementation (class template) | | Hashing | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | [std::hash<*Arithmetic*>std::hash<*Enumeration*>std::hash<std::nullptr\_t>std::hash<T\*>](../utility/hash "cpp/utility/hash") (C++11) | `[std::hash](../utility/hash "cpp/utility/hash")` specializations for fundamental, enumeration, and pointer types (class template specialization) | | Constants | | Defined in namespace `std::placeholders` | | [\_1, \_2, \_3, \_4, ...](../utility/functional/placeholders "cpp/utility/functional/placeholders") (C++11) | placeholders for the unbound arguments in a `std::bind` expression (constant) | | Functions | | [bind\_frontbind\_back](../utility/functional/bind_front "cpp/utility/functional/bind front") (C++20)(C++23) | bind a variable number of arguments, in order, to a function object (function template) | | [bind](../utility/functional/bind "cpp/utility/functional/bind") (C++11) | binds one or more arguments to a function object (function template) | | [refcref](../utility/functional/ref "cpp/utility/functional/ref") (C++11)(C++11) | creates a `[std::reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper")` with a type deduced from its argument (function template) | | [invokeinvoke\_r](../utility/functional/invoke "cpp/utility/functional/invoke") (C++17)(C++23) | invokes any [Callable](../named_req/callable "cpp/named req/Callable") object with given arguments and possibility to specify return type (since C++23) (function template) | ### Deprecated in C++11 and removed in C++17 | | | --- | | Base | | [unary\_function](../utility/functional/unary_function "cpp/utility/functional/unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible unary function base class (class template) | | [binary\_function](../utility/functional/binary_function "cpp/utility/functional/binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible binary function base class (class template) | | Binders | | [binder1stbinder2nd](../utility/functional/binder12 "cpp/utility/functional/binder12") (deprecated in C++11)(removed in C++17) | function object holding a binary function and one of its arguments (class template) | | [bind1stbind2nd](../utility/functional/bind12 "cpp/utility/functional/bind12") (deprecated in C++11)(removed in C++17) | binds one argument to a binary function (function template) | | Function adaptors | | [pointer\_to\_unary\_function](../utility/functional/pointer_to_unary_function "cpp/utility/functional/pointer to unary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to unary function (class template) | | [pointer\_to\_binary\_function](../utility/functional/pointer_to_binary_function "cpp/utility/functional/pointer to binary function") (deprecated in C++11)(removed in C++17) | adaptor-compatible wrapper for a pointer to binary function (class template) | | [ptr\_fun](../utility/functional/ptr_fun "cpp/utility/functional/ptr fun") (deprecated in C++11)(removed in C++17) | creates an adaptor-compatible function object wrapper from a pointer to function (function template) | | [mem\_fun\_tmem\_fun1\_tconst\_mem\_fun\_tconst\_mem\_fun1\_t](../utility/functional/mem_fun_t "cpp/utility/functional/mem fun t") (deprecated in C++11)(removed in C++17) | wrapper for a pointer to nullary or unary member function, callable with a pointer to object (class template) | | [mem\_fun](../utility/functional/mem_fun "cpp/utility/functional/mem fun") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a pointer to object (function template) | | [mem\_fun\_ref\_tmem\_fun1\_ref\_tconst\_mem\_fun\_ref\_tconst\_mem\_fun1\_ref\_t](../utility/functional/mem_fun_ref_t "cpp/utility/functional/mem fun ref t") (deprecated in C++11)(removed in C++17) | wrapper for a pointer to nullary or unary member function, callable with a reference to object (class template) | | [mem\_fun\_ref](../utility/functional/mem_fun_ref "cpp/utility/functional/mem fun ref") (deprecated in C++11)(removed in C++17) | creates a wrapper from a pointer to member function, callable with a reference to object (function template) | ### Deprecated in C++17 and removed in C++20 | | | --- | | Negators | | [unary\_negate](../utility/functional/unary_negate "cpp/utility/functional/unary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the unary predicate it holds (class template) | | [binary\_negate](../utility/functional/binary_negate "cpp/utility/functional/binary negate") (deprecated in C++17)(removed in C++20) | wrapper function object returning the complement of the binary predicate it holds (class template) | | [not1](../utility/functional/not1 "cpp/utility/functional/not1") (deprecated in C++17)(removed in C++20) | constructs custom `[std::unary\_negate](../utility/functional/unary_negate "cpp/utility/functional/unary negate")` object (function template) | | [not2](../utility/functional/not2 "cpp/utility/functional/not2") (deprecated in C++17)(removed in C++20) | constructs custom `[std::binary\_negate](../utility/functional/binary_negate "cpp/utility/functional/binary negate")` object (function template) | ### Synopsis ``` namespace std { // invoke template<class F, class... Args> constexpr invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) noexcept(is_nothrow_invocable_v<F, Args...>); template<class R, class F, class... Args> constexpr R invoke_r(F&& f, Args&&... args) noexcept(is_nothrow_invocable_r_v<R, F, Args...>); // reference_wrapper template<class T> class reference_wrapper; template<class T> constexpr reference_wrapper<T> ref(T&) noexcept; template<class T> constexpr reference_wrapper<const T> cref(const T&) noexcept; template<class T> void ref(const T&&) = delete; template<class T> void cref(const T&&) = delete; template<class T> constexpr reference_wrapper<T> ref(reference_wrapper<T>) noexcept; template<class T> constexpr reference_wrapper<const T> cref(reference_wrapper<T>) noexcept; template<class T> struct unwrap_reference; template<class T> using unwrap_reference_t = typename unwrap_reference<T>::type; template<class T> struct unwrap_ref_decay; template<class T> using unwrap_ref_decay_t = typename unwrap_ref_decay<T>::type; // arithmetic operations template<class T = void> struct plus; template<class T = void> struct minus; template<class T = void> struct multiplies; template<class T = void> struct divides; template<class T = void> struct modulus; template<class T = void> struct negate; template<> struct plus<void>; template<> struct minus<void>; template<> struct multiplies<void>; template<> struct divides<void>; template<> struct modulus<void>; template<> struct negate<void>; // comparisons template<class T = void> struct equal_to; template<class T = void> struct not_equal_to; template<class T = void> struct greater; template<class T = void> struct less; template<class T = void> struct greater_equal; template<class T = void> struct less_equal; template<> struct equal_to<void>; template<> struct not_equal_to<void>; template<> struct greater<void>; template<> struct less<void>; template<> struct greater_equal<void>; template<> struct less_equal<void>; // logical operations template<class T = void> struct logical_and; template<class T = void> struct logical_or; template<class T = void> struct logical_not; template<> struct logical_and<void>; template<> struct logical_or<void>; template<> struct logical_not<void>; // bitwise operations template<class T = void> struct bit_and; template<class T = void> struct bit_or; template<class T = void> struct bit_xor; template<class T = void> struct bit_not; template<> struct bit_and<void>; template<> struct bit_or<void>; template<> struct bit_xor<void>; template<> struct bit_not<void>; // identity struct identity; // function template not_fn template<class F> constexpr /* unspecified */ not_fn(F&& f); // function templates bind_front and bind_back template<class F, class... Args> constexpr /* unspecified */ bind_front(F&&, Args&&...); template<class F, class... Args> constexpr /* unspecified */ bind_back(F&&, Args&&...); // bind template<class T> struct is_bind_expression; template<class T> struct is_placeholder; template<class F, class... BoundArgs> constexpr /* unspecified */ bind(F&&, BoundArgs&&...); template<class R, class F, class... BoundArgs> constexpr /* unspecified */ bind(F&&, BoundArgs&&...); namespace placeholders { // M is the implementation-defined number of placeholders /* see description */ _1; /* see description */ _2; . . . /* see description */ _M; } // member function adaptors template<class R, class T> constexpr /* unspecified */ mem_fn(R T::*) noexcept; // polymorphic function wrappers class bad_function_call; template<class> class function; // not defined template<class R, class... ArgTypes> class function<R(ArgTypes...)>; template<class R, class... ArgTypes> void swap(function<R(ArgTypes...)>&, function<R(ArgTypes...)>&) noexcept; template<class R, class... ArgTypes> bool operator==(const function<R(ArgTypes...)>&, nullptr_t) noexcept; template<class...> class move_only_function; // not defined template<class R, class... ArgTypes> class move_only_function<R(ArgTypes...) /*cv ref*/ noexcept(/*noex*/)>; // searchers template<class ForwardIter, class BinaryPredicate = equal_to<>> class default_searcher; template<class RandomAccessIter, class Hash = hash<typename iterator_traits<RandomAccessIter>::value_type>, class BinaryPredicate = equal_to<>> class boyer_moore_searcher; template<class RandomAccessIter, class Hash = hash<typename iterator_traits<RandomAccessIter>::value_type>, class BinaryPredicate = equal_to<>> class boyer_moore_horspool_searcher; // hash function primary template template<class T> struct hash; // function object binders template<class T> inline constexpr bool is_bind_expression_v = is_bind_expression<T>::value; template<class T> inline constexpr int is_placeholder_v = is_placeholder<T>::value; namespace ranges { // concept-constrained comparisons struct equal_to; struct not_equal_to; struct greater; struct less; struct greater_equal; struct less_equal; } } ``` #### Class template `[std::reference\_wrapper](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper")` ``` namespace std { template<class T> class reference_wrapper { public: // types using type = T; // construct/copy/destroy template<class U> constexpr reference_wrapper(U&&) noexcept(see below); constexpr reference_wrapper(const reference_wrapper& x) noexcept; // assignment constexpr reference_wrapper& operator=(const reference_wrapper& x) noexcept; // access constexpr operator T& () const noexcept; constexpr T& get() const noexcept; // invocation template<class... ArgTypes> constexpr invoke_result_t<T&, ArgTypes...> operator()(ArgTypes&&...) const; }; template<class T> reference_wrapper(T&) -> reference_wrapper<T>; } ``` #### Class template `[std::unwrap\_reference](../utility/functional/unwrap_reference "cpp/utility/functional/unwrap reference")` ``` namespace std { template<class T> struct unwrap_reference; } ``` #### Class template `[std::unwrap\_ref\_decay](../utility/functional/unwrap_reference "cpp/utility/functional/unwrap reference")` ``` namespace std { template<class T> struct unwrap_ref_decay; } ``` #### Class template `[std::plus](../utility/functional/plus "cpp/utility/functional/plus")` ``` namespace std { template<class T = void> struct plus { constexpr T operator()(const T& x, const T& y) const; }; template<> struct plus<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) + std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::minus](../utility/functional/minus "cpp/utility/functional/minus")` ``` namespace std { template<class T = void> struct minus { constexpr T operator()(const T& x, const T& y) const; }; template<> struct minus<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) - std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::multiplies](../utility/functional/multiplies "cpp/utility/functional/multiplies")` ``` namespace std { template<class T = void> struct multiplies { constexpr T operator()(const T& x, const T& y) const; }; template<> struct multiplies<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) * std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::divides](../utility/functional/divides "cpp/utility/functional/divides")` ``` namespace std { template<class T = void> struct divides { constexpr T operator()(const T& x, const T& y) const; }; template<> struct divides<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) / std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::modulus](../utility/functional/modulus "cpp/utility/functional/modulus")` ``` namespace std { template<class T = void> struct modulus { constexpr T operator()(const T& x, const T& y) const; }; template<> struct modulus<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) % std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::negate](../utility/functional/negate "cpp/utility/functional/negate")` ``` namespace std { template<class T = void> struct negate { constexpr T operator()(const T& x) const; }; template<> struct negate<void> { template<class T> constexpr auto operator()(T&& t) const -> decltype(-std::forward<T>(t)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::equal\_to](../utility/functional/equal_to "cpp/utility/functional/equal to")` ``` namespace std { template<class T = void> struct equal_to { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct equal_to<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) == std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::not\_equal\_to](../utility/functional/not_equal_to "cpp/utility/functional/not equal to")` ``` namespace std { template<class T = void> struct not_equal_to { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct not_equal_to<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) != std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::greater](../utility/functional/greater "cpp/utility/functional/greater")` ``` namespace std { template<class T = void> struct greater { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct greater<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) > std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::less](../utility/functional/less "cpp/utility/functional/less")` ``` namespace std { template<class T = void> struct less { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct less<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) < std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::greater\_equal](../utility/functional/greater_equal "cpp/utility/functional/greater equal")` ``` namespace std { template<class T = void> struct greater_equal { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct greater_equal<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) >= std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::less\_equal](../utility/functional/less_equal "cpp/utility/functional/less equal")` ``` namespace std { template<class T = void> struct less_equal { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct less_equal<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) <= std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class `std::ranges::equal_to` ``` namespace std::ranges { struct equal_to { template<class T, class U> constexpr bool operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` #### Class `std::ranges::not_equal_to` ``` namespace std::ranges { struct not_equal_to { template<class T, class U> constexpr bool operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` #### Class `std::ranges::greater` ``` namespace std::ranges { struct greater { template<class T, class U> constexpr bool operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` #### Class `std::ranges::less` ``` namespace std::ranges { struct less { template<class T, class U> constexpr bool operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` #### Class `std::ranges::greater_equal` ``` namespace std::ranges { struct greater_equal { template<class T, class U> constexpr bool operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` #### Class `std::ranges::less_equal` ``` namespace std::ranges { struct less_equal { template<class T, class U> constexpr bool operator()(T&& t, U&& u) const; using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::logical\_and](../utility/functional/logical_and "cpp/utility/functional/logical and")` ``` namespace std { template<class T = void> struct logical_and { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct logical_and<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) && std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::logical\_or](../utility/functional/logical_or "cpp/utility/functional/logical or")` ``` namespace std { template<class T = void> struct logical_or { constexpr bool operator()(const T& x, const T& y) const; }; template<> struct logical_or<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) || std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::logical\_not](../utility/functional/logical_not "cpp/utility/functional/logical not")` ``` namespace std { template<class T = void> struct logical_not { constexpr bool operator()(const T& x) const; }; template<> struct logical_not<void> { template<class T> constexpr auto operator()(T&& t) const -> decltype(!std::forward<T>(t)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::bit\_and](../utility/functional/bit_and "cpp/utility/functional/bit and")` ``` namespace std { template<class T = void> struct bit_and { constexpr T operator()(const T& x, const T& y) const; }; template<> struct bit_and<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) & std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::bit\_or](../utility/functional/bit_or "cpp/utility/functional/bit or")` ``` namespace std { template<class T = void> struct bit_or { constexpr T operator()(const T& x, const T& y) const; }; template<> struct bit_or<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) | std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `std::bit_xor` ``` namespace std { template<class T = void> struct bit_xor { constexpr T operator()(const T& x, const T& y) const; }; template<> struct bit_xor<void> { template<class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) ^ std::forward<U>(u)); using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::bit\_not](../utility/functional/bit_not "cpp/utility/functional/bit not")` ``` namespace std { template<class T = void> struct bit_not { constexpr T operator()(const T& x) const; }; template<> struct bit_not<void> { template<class T> constexpr auto operator()(T&& t) const -> decltype(~std::forward<T>(t)); using is_transparent = /* unspecified */; }; } ``` #### Class template `std::identity` ``` namespace std { struct identity { template<class T> constexpr T&& operator()(T&& t) const noexcept; using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::is\_bind\_expression](../utility/functional/is_bind_expression "cpp/utility/functional/is bind expression")` ``` namespace std { template<class T> struct is_bind_expression; } ``` #### Class template `[std::is\_placeholder](../utility/functional/is_placeholder "cpp/utility/functional/is placeholder")` ``` namespace std { template<class T> struct is_placeholder; } ``` #### Class `[std::bad\_function\_call](../utility/functional/bad_function_call "cpp/utility/functional/bad function call")` ``` namespace std { class bad_function_call : public exception { public: // see [exception] for the specification of the special member functions const char* what() const noexcept override; }; } ``` #### Class template `[std::function](../utility/functional/function "cpp/utility/functional/function")` ``` namespace std { template<class> class function; // not defined template<class R, class... ArgTypes> class function<R(ArgTypes...)> { public: using result_type = R; // construct/copy/destroy function() noexcept; function(nullptr_t) noexcept; function(const function&); function(function&&) noexcept; template<class F> function(F); function& operator=(const function&); function& operator=(function&&); function& operator=(nullptr_t) noexcept; template<class F> function& operator=(F&&); template<class F> function& operator=(reference_wrapper<F>) noexcept; ~function(); // function modifiers void swap(function&) noexcept; // function capacity explicit operator bool() const noexcept; // function invocation R operator()(ArgTypes...) const; // function target access const type_info& target_type() const noexcept; template<class T> T* target() noexcept; template<class T> const T* target() const noexcept; }; template<class R, class... ArgTypes> function(R(*)(ArgTypes...)) -> function<R(ArgTypes...)>; template<class F> function(F) -> function</* see description */>; // null pointer comparison functions template<class R, class... ArgTypes> bool operator==(const function<R(ArgTypes...)>&, nullptr_t) noexcept; // specialized algorithms template<class R, class... ArgTypes> void swap(function<R(ArgTypes...)>&, function<R(ArgTypes...)>&) noexcept; } ``` #### Class template `std::move_only_function` ``` namespace std { template<class... S> class move_only_function; // not defined template<class R, class... ArgTypes> class move_only_function<R(ArgTypes...) /*cv-ref*/ noexcept(/*noex*/)> { public: using result_type = R; // construct/move/destroy move_only_function() noexcept; move_only_function(nullptr_t) noexcept; move_only_function(move_only_function&&) noexcept; template<class F> move_only_function(F&&); template<class T, class... Args> explicit move_only_function(in_place_type_t<T>, Args&&...); template<class T, class U, class... Args> explicit move_only_function(in_place_type_t<T>, initializer_list<U>, Args&&...); move_only_function& operator=(move_only_function&&); move_only_function& operator=(nullptr_t) noexcept; template<class F> move_only_function& operator=(F&&); ~move_only_function(); // move_only_function invocation explicit operator bool() const noexcept; R operator()(ArgTypes...) /*cv-ref*/ noexcept(/*noex*/); // move_only_function utility void swap(move_only_function&) noexcept; friend void swap(move_only_function&, move_only_function&) noexcept; friend bool operator==(const move_only_function&, nullptr_t) noexcept; private: template<class VT> static constexpr bool /*is-callable-from*/ = /* see description */; // exposition-only }; } ``` #### Class template `[std::default\_searcher](../utility/functional/default_searcher "cpp/utility/functional/default searcher")` ``` namespace std { template<class ForwardIter1, class BinaryPredicate = equal_to<>> class default_searcher { public: constexpr default_searcher(ForwardIter1 pat_first, ForwardIter1 pat_last, BinaryPredicate pred = BinaryPredicate()); template<class ForwardIter2> constexpr pair<ForwardIter2, ForwardIter2> operator()(ForwardIter2 first, ForwardIter2 last) const; private: ForwardIter1 pat_first_; // exposition only ForwardIter1 pat_last_; // exposition only BinaryPredicate pred_; // exposition only }; } ``` #### Class template `[std::boyer\_moore\_searcher](../utility/functional/boyer_moore_searcher "cpp/utility/functional/boyer moore searcher")` ``` namespace std { template<class RandomAccessIter1, class Hash = hash<typename iterator_traits<RandomAccessIter1>::value_type>, class BinaryPredicate = equal_to<>> class boyer_moore_searcher { public: boyer_moore_searcher(RandomAccessIter1 pat_first, RandomAccessIter1 pat_last, Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate()); template<class RandomAccessIter2> pair<RandomAccessIter2, RandomAccessIter2> operator()(RandomAccessIter2 first, RandomAccessIter2 last) const; private: RandomAccessIter1 pat_first_; // exposition only RandomAccessIter1 pat_last_; // exposition only Hash hash_; // exposition only BinaryPredicate pred_; // exposition only }; } ``` #### Class template `[std::boyer\_moore\_horspool\_searcher](../utility/functional/boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher")` ``` namespace std { template<class RandomAccessIter1, class Hash = hash<typename iterator_traits<RandomAccessIter1>::value_type>, class BinaryPredicate = equal_to<>> class boyer_moore_horspool_searcher { public: boyer_moore_horspool_searcher(RandomAccessIter1 pat_first, RandomAccessIter1 pat_last, Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate()); template<class RandomAccessIter2> pair<RandomAccessIter2, RandomAccessIter2> operator()(RandomAccessIter2 first, RandomAccessIter2 last) const; private: RandomAccessIter1 pat_first_; // exposition only RandomAccessIter1 pat_last_; // exposition only Hash hash_; // exposition only BinaryPredicate pred_; // exposition only }; } ``` ### See also | | | | --- | --- | | [`<string>`](string "cpp/header/string") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::string](../string/basic_string "cpp/string/basic string")`, `[std::u16string](../string/basic_string "cpp/string/basic string")`, `[std::u32string](../string/basic_string "cpp/string/basic string")`, `[std::wstring](../string/basic_string "cpp/string/basic string")` | | [`<string_view>`](string_view "cpp/header/string view") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::string\_view](../string/basic_string_view "cpp/string/basic string view")`, `[std::u16string\_view](../string/basic_string_view "cpp/string/basic string view")`, `[std::u32string\_view](../string/basic_string_view "cpp/string/basic string view")`, `[std::wstring\_view](../string/basic_string_view "cpp/string/basic string view")` | | [`<system_error>`](system_error "cpp/header/system error") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::error\_code](../error/error_code "cpp/error/error code")` | | [`<bitset>`](bitset "cpp/header/bitset") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::bitset](../utility/bitset "cpp/utility/bitset")` | | [`<memory>`](memory "cpp/header/memory") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")`, `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` | | [`<typeindex>`](typeindex "cpp/header/typeindex") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::type\_index](../types/type_index "cpp/types/type index")` | | [`<vector>`](vector "cpp/header/vector") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>` | | [`<thread>`](thread "cpp/header/thread") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::thread::id](../thread/thread/id "cpp/thread/thread/id")` | | [`<optional>`](optional "cpp/header/optional") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::optional](../utility/optional "cpp/utility/optional")` | | [`<variant>`](variant "cpp/header/variant") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::variant](../utility/variant "cpp/utility/variant")` | | [`<coroutine>`](coroutine "cpp/header/coroutine") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `[std::coroutine\_handle](../coroutine/coroutine_handle "cpp/coroutine/coroutine handle")` | | [`<stacktrace>`](stacktrace "cpp/header/stacktrace") | Specializes `[std::hash](../utility/hash "cpp/utility/hash")` for `std::stacktrace_entry` and `std::basic_stacktrace` |
programming_docs
cpp Standard library header <coroutine> (C++20) Standard library header <coroutine> (C++20) =========================================== This header is part of the [coroutine support](../coroutine "cpp/coroutine") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [coroutine\_traits](../coroutine/coroutine_traits "cpp/coroutine/coroutine traits") (C++20) | trait type for discovering coroutine promise types (class template) | | [coroutine\_handle](../coroutine/coroutine_handle "cpp/coroutine/coroutine handle") (C++20) | used to refer to a suspended or executing coroutine (class template) | | [std::hash<std::coroutine\_handle>](../coroutine/coroutine_handle/hash "cpp/coroutine/coroutine handle/hash") (C++20) | hash support for `[std::coroutine\_handle](../coroutine/coroutine_handle "cpp/coroutine/coroutine handle")` (class template specialization) | | No-op Coroutines | | [noop\_coroutine\_promise](../coroutine/noop_coroutine_promise "cpp/coroutine/noop coroutine promise") (C++20) | used for coroutines with no observable effects (class) | | [noop\_coroutine\_handle](../coroutine/coroutine_handle "cpp/coroutine/coroutine handle") (C++20) | `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>`, intended to refer to a no-op coroutine (typedef) | | Trivial Awaitables | | [suspend\_never](../coroutine/suspend_never "cpp/coroutine/suspend never") (C++20) | indicates that an await-expression should never suspend (class) | | [suspend\_always](../coroutine/suspend_always "cpp/coroutine/suspend always") (C++20) | indicates that an await-expression should always suspend (class) | | Functions | | [operator==operator<=>](../coroutine/coroutine_handle/operator_cmp "cpp/coroutine/coroutine handle/operator cmp") (C++20) | compares two `coroutine_handle` objects (function) | | No-op Coroutines | | [noop\_coroutine](../coroutine/noop_coroutine "cpp/coroutine/noop coroutine") (C++20) | creates a coroutine handle that has no observable effects when resumed or destroyed (function) | ### Synopsis ``` #include <compare> namespace std { // coroutine traits template<class R, class... ArgTypes> struct coroutine_traits; // coroutine handle template<class Promise = void> struct coroutine_handle; // comparison operators constexpr bool operator==(coroutine_handle<> x, coroutine_handle<> y) noexcept; constexpr strong_ordering operator<=>(coroutine_handle<> x, coroutine_handle<> y) noexcept; // hash support template<class T> struct hash; template<class P> struct hash<coroutine_handle<P>>; // no-op coroutines struct noop_coroutine_promise; template<> struct coroutine_handle<noop_coroutine_promise>; using noop_coroutine_handle = coroutine_handle<noop_coroutine_promise>; noop_coroutine_handle noop_coroutine() noexcept; // trivial awaitables struct suspend_never; struct suspend_always; } ``` #### Class template `[std::coroutine\_handle](../coroutine/coroutine_handle "cpp/coroutine/coroutine handle")` ``` namespace std { template<> struct coroutine_handle<void> { // construct/reset constexpr coroutine_handle() noexcept; constexpr coroutine_handle(nullptr_t) noexcept; coroutine_handle& operator=(nullptr_t) noexcept; // export/import constexpr void* address() const noexcept; static constexpr coroutine_handle from_address(void* addr); // observers constexpr explicit operator bool() const noexcept; bool done() const; // resumption void operator()() const; void resume() const; void destroy() const; private: void* ptr; // exposition only }; template<class Promise> struct coroutine_handle { // construct/reset constexpr coroutine_handle() noexcept; constexpr coroutine_handle(nullptr_t) noexcept; static coroutine_handle from_promise(Promise&); coroutine_handle& operator=(nullptr_t) noexcept; // export/import constexpr void* address() const noexcept; static constexpr coroutine_handle from_address(void* addr); // conversion constexpr operator coroutine_handle<>() const noexcept; // observers constexpr explicit operator bool() const noexcept; bool done() const; // resumption void operator()() const; void resume() const; void destroy() const; // promise access Promise& promise() const; private: void* ptr; // exposition only }; } ``` #### Class `[std::noop\_coroutine\_promise](../coroutine/noop_coroutine_promise "cpp/coroutine/noop coroutine promise")` ``` namespace std { struct noop_coroutine_promise {}; } ``` #### Class `[std::coroutine\_handle](http://en.cppreference.com/w/cpp/coroutine/coroutine_handle)<[std::noop\_coroutine\_promise](http://en.cppreference.com/w/cpp/coroutine/noop_coroutine_promise)>` ``` namespace std { template<> struct coroutine_handle<noop_coroutine_promise> { // conversion constexpr operator coroutine_handle<>() const noexcept; // observers constexpr explicit operator bool() const noexcept; constexpr bool done() const noexcept; // resumption constexpr void operator()() const noexcept; constexpr void resume() const noexcept; constexpr void destroy() const noexcept; // promise access noop_coroutine_promise& promise() const noexcept; // address constexpr void* address() const noexcept; private: coroutine_handle(/* unspecified */); void* ptr; // exposition only }; } ``` #### Class `[std::suspend\_never](../coroutine/suspend_never "cpp/coroutine/suspend never")` ``` namespace std { struct suspend_never { constexpr bool await_ready() const noexcept { return true; } constexpr void await_suspend(coroutine_handle<>) const noexcept {} constexpr void await_resume() const noexcept {} }; } ``` #### Class `[std::suspend\_always](../coroutine/suspend_always "cpp/coroutine/suspend always")` ``` namespace std { struct suspend_always { constexpr bool await_ready() const noexcept { return false; } constexpr void await_suspend(coroutine_handle<>) const noexcept {} constexpr void await_resume() const noexcept {} }; } ``` cpp Standard library header <typeindex> (C++11) Standard library header <typeindex> (C++11) =========================================== This header is part of the [types support](../types "cpp/types") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [type\_index](../types/type_index "cpp/types/type index") (C++11) | wrapper around a `type_info` object, that can be used as index in associative and unordered associative containers (class) | | [std::hash<std::type\_index>](../types/type_index/hash "cpp/types/type index/hash") (C++11) | hash support for `[std::type\_index](../types/type_index "cpp/types/type index")` (class template specialization) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | ### Synopsis ``` #include <compare> namespace std { class type_index; template<class T> struct hash; template<> struct hash<type_index>; } ``` #### Class `[std::type\_index](../types/type_index "cpp/types/type index")` ``` namespace std { class type_index { public: type_index(const type_info& rhs) noexcept; bool operator==(const type_index& rhs) const noexcept; bool operator< (const type_index& rhs) const noexcept; bool operator> (const type_index& rhs) const noexcept; bool operator<=(const type_index& rhs) const noexcept; bool operator>=(const type_index& rhs) const noexcept; strong_ordering operator<=>(const type_index& rhs) const noexcept; size_t hash_code() const noexcept; const char* name() const noexcept; private: const type_info* target; // exposition only // Note that the use of a pointer here, rather than a reference, // means that the default copy/move constructor and assignment // operators will be provided and work as expected. }; } ``` cpp Standard library header <ccomplex> (C++11)(until C++20), <complex.h> (C++11) Standard library header <ccomplex> (C++11)(until C++20), <complex.h> (C++11) ============================================================================ This header was originally in the C standard library as `<complex.h>`. | | | --- | | Includes | | [<complex>](complex "cpp/header/complex") (C++11) | [Complex number type](../numeric/complex "cpp/numeric/complex") | ### Notes `<ccomplex>` is deprecated in C++17 and removed in C++20. Corresponding `<complex.h>` is still available in C++20. cpp Standard library header <ios> Standard library header <ios> ============================= This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Includes | | [<iosfwd>](iosfwd "cpp/header/iosfwd") | Forward declarations of all classes in the input/output library | | Classes | | [ios\_base](../io/ios_base "cpp/io/ios base") | manages formatting flags and input/output exceptions (class) | | [basic\_ios](../io/basic_ios "cpp/io/basic ios") | manages an arbitrary stream buffer (class template) | | [`std::ios`](../io/basic_ios "cpp/io/basic ios") | `[std::basic\_ios](http://en.cppreference.com/w/cpp/io/basic_ios)<char>` (typedef) | | [`std::wios`](../io/basic_ios "cpp/io/basic ios") | `[std::basic\_ios](http://en.cppreference.com/w/cpp/io/basic_ios)<wchar\_t>` (typedef) | | [fpos](../io/fpos "cpp/io/fpos") | represents absolute position in a stream or a file (class template) | | [io\_errc](../io/io_errc "cpp/io/io errc") (C++11) | the IO stream error codes (enum) | | [is\_error\_code\_enum<std::io\_errc>](../io/io_errc/is_error_code_enum "cpp/io/io errc/is error code enum") (C++11) | extends the type trait `[std::is\_error\_code\_enum](../error/error_code/is_error_code_enum "cpp/error/error code/is error code enum")` to identify iostream error codes (class template specialization) | | [streamoff](../io/streamoff "cpp/io/streamoff") | represents relative file/stream position (offset from fpos), sufficient to represent any file size (typedef) | | [streamsize](../io/streamsize "cpp/io/streamsize") | represents the number of characters transferred in an I/O operation or the size of an I/O buffer (typedef) | | Functions | | [iostream\_category](../io/iostream_category "cpp/io/iostream category") (C++11) | identifies the iostream error category (function) | | [make\_error\_code(std::io\_errc)](../io/io_errc/make_error_code "cpp/io/io errc/make error code") (C++11) | constructs an iostream error code (function) | | [make\_error\_condition(std::io\_errc)](../io/io_errc/make_error_condition "cpp/io/io errc/make error condition") (C++11) | constructs an iostream error code (function) | | [boolalphanoboolalpha](../io/manip/boolalpha "cpp/io/manip/boolalpha") | switches between textual and numeric representation of booleans (function) | | [showbasenoshowbase](../io/manip/showbase "cpp/io/manip/showbase") | controls whether prefix is used to indicate numeric base (function) | | [showpointnoshowpoint](../io/manip/showpoint "cpp/io/manip/showpoint") | controls whether decimal point is always included in floating-point representation (function) | | [showposnoshowpos](../io/manip/showpos "cpp/io/manip/showpos") | controls whether the `+` sign used with non-negative numbers (function) | | [skipwsnoskipws](../io/manip/skipws "cpp/io/manip/skipws") | controls whether leading whitespace is skipped on input (function) | | [uppercasenouppercase](../io/manip/uppercase "cpp/io/manip/uppercase") | controls whether uppercase characters are used with some output formats (function) | | [unitbufnounitbuf](../io/manip/unitbuf "cpp/io/manip/unitbuf") | controls whether output is flushed after each operation (function) | | [internalleftright](../io/manip/left "cpp/io/manip/left") | sets the placement of fill characters (function) | | [dechexoct](../io/manip/hex "cpp/io/manip/hex") | changes the base used for integer I/O (function) | | [fixedscientifichexfloatdefaultfloat](../io/manip/fixed "cpp/io/manip/fixed") (C++11)(C++11) | changes formatting used for floating-point I/O (function) | ### Synopsis ``` #include <iosfwd> namespace std { using streamoff = /* implementation-defined */; using streamsize = /* implementation-defined */; template<class StateT> class fpos; class ios_base; template<class CharT, class Traits = char_traits<CharT>> class basic_ios; // manipulators ios_base& boolalpha (ios_base& str); ios_base& noboolalpha(ios_base& str); ios_base& showbase (ios_base& str); ios_base& noshowbase (ios_base& str); ios_base& showpoint (ios_base& str); ios_base& noshowpoint(ios_base& str); ios_base& showpos (ios_base& str); ios_base& noshowpos (ios_base& str); ios_base& skipws (ios_base& str); ios_base& noskipws (ios_base& str); ios_base& uppercase (ios_base& str); ios_base& nouppercase(ios_base& str); ios_base& unitbuf (ios_base& str); ios_base& nounitbuf (ios_base& str); // adjustfield ios_base& internal (ios_base& str); ios_base& left (ios_base& str); ios_base& right (ios_base& str); // basefield ios_base& dec (ios_base& str); ios_base& hex (ios_base& str); ios_base& oct (ios_base& str); // floatfield ios_base& fixed (ios_base& str); ios_base& scientific (ios_base& str); ios_base& hexfloat (ios_base& str); ios_base& defaultfloat(ios_base& str); // error reporting enum class io_errc { stream = 1 }; template<> struct is_error_code_enum<io_errc> : public true_type { }; error_code make_error_code(io_errc e) noexcept; error_condition make_error_condition(io_errc e) noexcept; const error_category& iostream_category() noexcept; } ``` #### Class `[std::ios\_base](../io/ios_base "cpp/io/ios base")` ``` namespace std { class ios_base { public: class failure; // see description // fmtflags using fmtflags = /*bitmask-type-1*/; static constexpr fmtflags boolalpha = /* unspecified */; static constexpr fmtflags dec = /* unspecified */; static constexpr fmtflags fixed = /* unspecified */; static constexpr fmtflags hex = /* unspecified */; static constexpr fmtflags internal = /* unspecified */; static constexpr fmtflags left = /* unspecified */; static constexpr fmtflags oct = /* unspecified */; static constexpr fmtflags right = /* unspecified */; static constexpr fmtflags scientific = /* unspecified */; static constexpr fmtflags showbase = /* unspecified */; static constexpr fmtflags showpoint = /* unspecified */; static constexpr fmtflags showpos = /* unspecified */; static constexpr fmtflags skipws = /* unspecified */; static constexpr fmtflags unitbuf = /* unspecified */; static constexpr fmtflags uppercase = /* unspecified */; static constexpr fmtflags adjustfield = /* see description */; static constexpr fmtflags basefield = /* see description */; static constexpr fmtflags floatfield = /* see description */; // iostate using iostate = /*bitmask-type-2*/; static constexpr iostate badbit = /* unspecified */; static constexpr iostate eofbit = /* unspecified */; static constexpr iostate failbit = /* unspecified */; static constexpr iostate goodbit = /* see description */; // openmode using openmode = /*bitmask-type-3*/; static constexpr openmode app = /* unspecified */; static constexpr openmode ate = /* unspecified */; static constexpr openmode binary = /* unspecified */; static constexpr openmode in = /* unspecified */; static constexpr openmode out = /* unspecified */; static constexpr openmode trunc = /* unspecified */; // seekdir using seekdir = /*bitmask-type-4*/; static constexpr seekdir beg = /* unspecified */; static constexpr seekdir cur = /* unspecified */; static constexpr seekdir end = /* unspecified */; class Init; // fmtflags state fmtflags flags() const; fmtflags flags(fmtflags fmtfl); fmtflags setf(fmtflags fmtfl); fmtflags setf(fmtflags fmtfl, fmtflags mask); void unsetf(fmtflags mask); streamsize precision() const; streamsize precision(streamsize prec); streamsize width() const; streamsize width(streamsize wide); // locales locale imbue(const locale& loc); locale getloc() const; // storage static int xalloc(); long& iword(int idx); void*& pword(int idx); // destructor virtual ~ios_base(); // callbacks enum event { erase_event, imbue_event, copyfmt_event }; using event_callback = void (*)(event, ios_base&, int idx); void register_callback(event_callback fn, int idx); ios_base(const ios_base&) = delete; ios_base& operator=(const ios_base&) = delete; static bool sync_with_stdio(bool sync = true); protected: ios_base(); private: static int index; // exposition only long* iarray; // exposition only void** parray; // exposition only }; } ``` #### Class `[std::ios\_base::failure](../io/ios_base/failure "cpp/io/ios base/failure")` ``` namespace std { class ios_base::failure : public system_error { public: explicit failure(const string& msg, const error_code& ec = io_errc::stream); explicit failure(const char* msg, const error_code& ec = io_errc::stream); }; } ``` #### Class `[std::ios\_base::Init](../io/ios_base/init "cpp/io/ios base/Init")` ``` namespace std { class ios_base::Init { public: Init(); Init(const Init&) = default; ~Init(); Init& operator=(const Init&) = default; private: static int init_cnt; // exposition only }; } ``` #### Class template `[std::fpos](../io/fpos "cpp/io/fpos")` ``` namespace std { template<class StateT> class fpos { public: // members StateT state() const; void state(stateT); private; StateT st; // exposition only }; } ``` #### Class template `[std::basic\_ios](../io/basic_ios "cpp/io/basic ios")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ios : public ios_base { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // flags functions explicit operator bool() const; bool operator!() const; iostate rdstate() const; void clear(iostate state = goodbit); void setstate(iostate state); bool good() const; bool eof() const; bool fail() const; bool bad() const; iostate exceptions() const; void exceptions(iostate except); // constructor/destructor explicit basic_ios(basic_streambuf<CharT, Traits>* sb); virtual ~basic_ios(); // members basic_ostream<CharT, Traits>* tie() const; basic_ostream<CharT, Traits>* tie(basic_ostream<CharT, Traits>* tiestr); basic_streambuf<CharT, Traits>* rdbuf() const; basic_streambuf<CharT, Traits>* rdbuf(basic_streambuf<CharT, Traits>* sb); basic_ios& copyfmt(const basic_ios& rhs); char_type fill() const; char_type fill(char_type ch); locale imbue(const locale& loc); char narrow(char_type c, char dfault) const; char_type widen(char c) const; basic_ios(const basic_ios&) = delete; basic_ios& operator=(const basic_ios&) = delete; protected: basic_ios(); void init(basic_streambuf<CharT, Traits>* sb); void move(basic_ios& rhs); void move(basic_ios&& rhs); void swap(basic_ios& rhs) noexcept; void set_rdbuf(basic_streambuf<CharT, Traits>* sb); }; } ``` ### 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 35](https://cplusplus.github.io/LWG/issue35) | C++98 | the prototypes of `unitbuf` and `nounitbuf` were missing in the synopsis | added | | [LWG 78](https://cplusplus.github.io/LWG/issue78) | C++98 | the type of parameter `fn` of [`ios_base::register_callback`](../io/ios_base/register_callback "cpp/io/ios base/register callback")in the synopsis was misspecified as `event_call_back` | corrected to`event_callback` |
programming_docs
cpp Standard library header <print> (C++23) Standard library header <print> (C++23) ======================================= This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Functions | | [print](../io/print "cpp/io/print") (C++23) | prints to `[stdout](../io/c/std_streams "cpp/io/c/std streams")` or a file stream using [formatted](../utility/format "cpp/utility/format") representation of the arguments (function template) | | [println](../io/println "cpp/io/println") (C++23) | same as `std::print` except that each print is terminated by additional new line (function template) | | [vprint\_unicode](../io/vprint_unicode "cpp/io/vprint unicode") (C++23) | prints to Unicode capable `[stdout](../io/c/std_streams "cpp/io/c/std streams")` or a file stream using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | | [vprint\_nonunicode](../io/vprint_nonunicode "cpp/io/vprint nonunicode") (C++23) | prints to `[stdout](../io/c/std_streams "cpp/io/c/std streams")` or a file stream using [type-erased](../utility/format/basic_format_args "cpp/utility/format/basic format args") argument representation (function) | ### Synopsis ``` namespace std { // print functions template<class... Args> void print(format_string<Args...> fmt, Args&&... args); template<class... Args> void print(FILE* stream, format_string<Args...> fmt, Args&&... args); template<class... Args> void println(format_string<Args...> fmt, Args&&... args); template<class... Args> void println(FILE* stream, format_string<Args...> fmt, Args&&... args); void vprint_unicode(string_view fmt, format_args args); void vprint_unicode(FILE* stream, string_view fmt, format_args args); void vprint_nonunicode(string_view fmt, format_args args); void vprint_nonunicode(FILE* stream, string_view fmt, format_args args); } ``` ### References * C++23 standard (ISO/IEC 14882:2023): + 31.7.4 Header `<print>` synopsis [print.syn] + 31.7.10 Print functions [print.fun] cpp Standard library header <iosfwd> Standard library header <iosfwd> ================================ This header contains forward declarations for the [Input/output](../io "cpp/io") library. | | | --- | | Forward declarations | | Defined in header `[<string>](string "cpp/header/string")` | | `[std::char\_traits](../string/char_traits "cpp/string/char traits")` | Class Template which describes properties of a character type (class template) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char>` | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<wchar\_t>` | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char8_t>` (C++20) | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char16\_t>` (C++11) | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char32\_t>` (C++11) | (class template specialization) | | Defined in header `[<memory>](memory "cpp/header/memory")` | | [allocator](../memory/allocator "cpp/memory/allocator") | the default allocator (class template) | | Defined in header `[<ios>](ios "cpp/header/ios")` | | [basic\_ios](../io/basic_ios "cpp/io/basic ios") | manages an arbitrary stream buffer (class template) | | [fpos](../io/fpos "cpp/io/fpos") | represents absolute position in a stream or a file (class template) | | Defined in header `[<streambuf>](streambuf "cpp/header/streambuf")` | | [basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf") | abstracts a raw device (class template) | | Defined in header `[<ostream>](ostream "cpp/header/ostream")` | | [basic\_ostream](../io/basic_ostream "cpp/io/basic ostream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level output interface (class template) | | Defined in header `[<istream>](istream "cpp/header/istream")` | | [basic\_istream](../io/basic_istream "cpp/io/basic istream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level input interface (class template) | | [basic\_iostream](../io/basic_iostream "cpp/io/basic iostream") | wraps a given abstract device (`[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")`) and provides high-level input/output interface (class template) | | Defined in header `[<fstream>](fstream "cpp/header/fstream")` | | [basic\_filebuf](../io/basic_filebuf "cpp/io/basic filebuf") | implements raw file device (class template) | | [basic\_ifstream](../io/basic_ifstream "cpp/io/basic ifstream") | implements high-level file stream input operations (class template) | | [basic\_ofstream](../io/basic_ofstream "cpp/io/basic ofstream") | implements high-level file stream output operations (class template) | | [basic\_fstream](../io/basic_fstream "cpp/io/basic fstream") | implements high-level file stream input/output operations (class template) | | Defined in header `[<sstream>](sstream "cpp/header/sstream")` | | [basic\_stringbuf](../io/basic_stringbuf "cpp/io/basic stringbuf") | implements raw string device (class template) | | [basic\_istringstream](../io/basic_istringstream "cpp/io/basic istringstream") | implements high-level string stream input operations (class template) | | [basic\_ostringstream](../io/basic_ostringstream "cpp/io/basic ostringstream") | implements high-level string stream output operations (class template) | | [basic\_stringstream](../io/basic_stringstream "cpp/io/basic stringstream") | implements high-level string stream input/output operations (class template) | | Defined in header `[<syncstream>](syncstream "cpp/header/syncstream")` | | [basic\_syncbuf](../io/basic_syncbuf "cpp/io/basic syncbuf") (C++20) | synchronized output device wrapper (class template) | | [basic\_osyncstream](../io/basic_osyncstream "cpp/io/basic osyncstream") (C++20) | synchronized output stream wrapper (class template) | | Defined in header `[<spanstream>](spanstream "cpp/header/spanstream")` | | [basic\_spanbuf](../io/basic_spanbuf "cpp/io/basic spanbuf") (C++23) | implements raw fixed character buffer device (class template) | | [basic\_ispanstream](../io/basic_ispanstream "cpp/io/basic ispanstream") (C++23) | implements fixed character buffer input operations (class template) | | [basic\_ospanstream](../io/basic_ospanstream "cpp/io/basic ospanstream") (C++23) | implements fixed character buffer output operations (class template) | | [basic\_spanstream](../io/basic_spanstream "cpp/io/basic spanstream") (C++23) | implements fixed character buffer input/output operations (class template) | | Defined in header `[<strstream>](strstream "cpp/header/strstream")` | | [strstreambuf](../io/strstreambuf "cpp/io/strstreambuf") (deprecated in C++98) | implements raw character array device (class) | | [istrstream](../io/istrstream "cpp/io/istrstream") (deprecated in C++98) | implements character array input operations (class) | | [ostrstream](../io/ostrstream "cpp/io/ostrstream") (deprecated in C++98) | implements character array output operations (class) | | [strstream](../io/strstream "cpp/io/strstream") (deprecated in C++98) | implements character array input/output operations (class) | | Typedefs and specializations | | `[std::streampos](../io/fpos "cpp/io/fpos")` | `[std::fpos](http://en.cppreference.com/w/cpp/io/fpos)<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char>::state\_type>` | | `[std::wstreampos](../io/fpos "cpp/io/fpos")` | `[std::fpos](http://en.cppreference.com/w/cpp/io/fpos)<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<wchar\_t>::state\_type>` | | `[std::u8streampos](../io/fpos "cpp/io/fpos")` | `[std::fpos](http://en.cppreference.com/w/cpp/io/fpos)<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char8_t>::state\_type>` | | `[std::u16streampos](../io/fpos "cpp/io/fpos")` | `[std::fpos](http://en.cppreference.com/w/cpp/io/fpos)<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char16\_t>::state\_type>` | | `[std::u32streampos](../io/fpos "cpp/io/fpos")` | `[std::fpos](http://en.cppreference.com/w/cpp/io/fpos)<[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char32\_t>::state\_type>` | | In addition, for each class template `std::basic_*T*` declared in this header, `std::*T*` and `std::w*T*` are declared as a synonym of `std::basic_*T*<char>` and `std::basic_*T*<wchar_t>` respectively. | ### Synopsis ``` namespace std { template<class CharT> struct char_traits; template<> struct char_traits<char>; template<> struct char_traits<char8_t>; template<> struct char_traits<char16_t>; template<> struct char_traits<char32_t>; template<> struct char_traits<wchar_t>; template<class T> class allocator; template<class CharT, class Traits = char_traits<CharT>> class basic_ios; template<class CharT, class Traits = char_traits<CharT>> class basic_streambuf; template<class CharT, class Traits = char_traits<CharT>> class basic_istream; template<class CharT, class Traits = char_traits<CharT>> class basic_ostream; template<class CharT, class Traits = char_traits<CharT>> class basic_iostream; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_stringbuf; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_istringstream; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_ostringstream; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_stringstream; template<class CharT, class Traits = char_traits<CharT>> class basic_filebuf; template<class CharT, class Traits = char_traits<CharT>> class basic_ifstream; template<class CharT, class Traits = char_traits<CharT>> class basic_ofstream; template<class CharT, class Traits = char_traits<CharT>> class basic_fstream; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_syncbuf; template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_osyncstream; template<class CharT, class Traits = char_traits<CharT>> class basic_spanbuf; template<class CharT, class Traits = char_traits<CharT>> class basic_ispanstream; template<class CharT, class Traits = char_traits<CharT>> class basic_ospanstream; template<class CharT, class Traits = char_traits<CharT>> class basic_spanstream; template<class CharT, class Traits = char_traits<CharT>> class istreambuf_iterator; template<class CharT, class Traits = char_traits<CharT>> class ostreambuf_iterator; using ios = basic_ios<char>; using wios = basic_ios<wchar_t>; using streambuf = basic_streambuf<char>; using istream = basic_istream<char>; using ostream = basic_ostream<char>; using iostream = basic_iostream<char>; using stringbuf = basic_stringbuf<char>; using istringstream = basic_istringstream<char>; using ostringstream = basic_ostringstream<char>; using stringstream = basic_stringstream<char>; using filebuf = basic_filebuf<char>; using ifstream = basic_ifstream<char>; using ofstream = basic_ofstream<char>; using fstream = basic_fstream<char>; using syncbuf = basic_syncbuf<char>; using osyncstream = basic_osyncstream<char>; using spanbuf = basic_spanbuf<char>; using ispanstream = basic_ispanstream<char>; using ospanstream = basic_ospanstream<char>; using spanstream = basic_spanstream<char>; using wstreambuf = basic_streambuf<wchar_t>; using wistream = basic_istream<wchar_t>; using wostream = basic_ostream<wchar_t>; using wiostream = basic_iostream<wchar_t>; using wstringbuf = basic_stringbuf<wchar_t>; using wistringstream = basic_istringstream<wchar_t>; using wostringstream = basic_ostringstream<wchar_t>; using wstringstream = basic_stringstream<wchar_t>; using wfilebuf = basic_filebuf<wchar_t>; using wifstream = basic_ifstream<wchar_t>; using wofstream = basic_ofstream<wchar_t>; using wfstream = basic_fstream<wchar_t>; using wsyncbuf = basic_syncbuf<wchar_t>; using wosyncstream = basic_osyncstream<wchar_t>; using wspanbuf = basic_spanbuf<wchar_t>; using wispanstream = basic_ispanstream<wchar_t>; using wospanstream = basic_ospanstream<wchar_t>; using wspanstream = basic_spanstream<wchar_t>; template<class State> class fpos; using streampos = fpos<char_traits<char>::state_type>; using wstreampos = fpos<char_traits<wchar_t>::state_type>; using u8streampos = fpos<char_traits<char8_t>::state_type>; using u16streampos = fpos<char_traits<char16_t>::state_type>; using u32streampos = fpos<char_traits<char32_t>::state_type>; } // deprecated namespace std { class strstreambuf; class istrstream; class ostrstream; class strstream; } ``` cpp Standard library header <barrier> (C++20) Standard library header <barrier> (C++20) ========================================= This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [barrier](../thread/barrier "cpp/thread/barrier") (C++20) | reusable thread barrier (class template) | ### Synopsis ``` namespace std { template<class CompletionFunction = /* see description */> class barrier; } ``` #### Class template `[std::barrier](../thread/barrier "cpp/thread/barrier")` ``` namespace std { template<class CompletionFunction = /* see description */> class barrier { public: using arrival_token = /* see description */; static constexpr ptrdiff_t max() noexcept; constexpr explicit barrier(ptrdiff_t expected, CompletionFunction f = CompletionFunction()); ~barrier(); barrier(const barrier&) = delete; barrier& operator=(const barrier&) = delete; [[nodiscard]] arrival_token arrive(ptrdiff_t update = 1); void wait(arrival_token&& arrival) const; void arrive_and_wait(); void arrive_and_drop(); private: CompletionFunction completion; // exposition only }; } ``` cpp Standard library header <cuchar> (C++11) Standard library header <cuchar> (C++11) ======================================== This header was originally in the C standard library as `<uchar.h>`. This header is part of the [null-terminated multibyte strings](../string/multibyte "cpp/string/multibyte") library. | | | --- | | Macros | | \_\_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) | | Types | | [mbstate\_t](../string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") | conversion state information necessary to iterate multibyte character strings (class) | | [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) | | Functions | | [mbrtoc16](../string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") (C++11) | Converts a narrow multibyte character to UTF-16 encoding (function) | | [c16rtomb](../string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb") (C++11) | convert a 16-bit wide character to narrow multibyte string (function) | | [mbrtoc32](../string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") (C++11) | converts a narrow multibyte character to UTF-32 encoding (function) | | [c32rtomb](../string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb") (C++11) | convert a 32-bit wide character to narrow multibyte string (function) | | [mbrtoc8](../string/multibyte/mbrtoc8 "cpp/string/multibyte/mbrtoc8") (C++20) | converts a narrow multibyte character to UTF-8 encoding (function) | | [c8rtomb](../string/multibyte/c8rtomb "cpp/string/multibyte/c8rtomb") (C++20) | converts UTF-8 string to narrow multibyte encoding (function) | ### Synopsis ``` namespace std { using mbstate_t = /* see description */; using size_t = /* see description */; size_t mbrtoc8(char8_t* pc8, const char* s, size_t n, mbstate_t* ps); size_t c8rtomb(char* s, char8_t c8, mbstate_t* ps); size_t mbrtoc16(char16_t* pc16, const char* s, size_t n, mbstate_t* ps); size_t c16rtomb(char* s, char16_t c16, mbstate_t* ps); size_t mbrtoc32(char32_t* pc32, const char* s, size_t n, mbstate_t* ps); size_t c32rtomb(char* s, char32_t c32, mbstate_t* ps); } ``` cpp Standard library header <string> Standard library header <string> ================================ This header is part of the [strings](../string "cpp/string") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [char\_traits](../string/char_traits "cpp/string/char traits") | Class Template which describes properties of a character type (class template) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char>` | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<wchar\_t>` | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char8_t>` (C++20) | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char16\_t>` (C++11) | (class template specialization) | | `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<char32\_t>` (C++11) | (class template specialization) | | [basic\_string](../string/basic_string "cpp/string/basic string") | stores and manipulates sequences of characters (class template) | | `[std::string](../string/basic_string "cpp/string/basic string")` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char>` (typedef) | | `[std::u8string](../string/basic_string "cpp/string/basic string")` (C++20) | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char8_t>` (typedef) | | `[std::u16string](../string/basic_string "cpp/string/basic string")` (C++11) | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char16\_t>` (typedef) | | `[std::u32string](../string/basic_string "cpp/string/basic string")` (C++11) | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char32\_t>` (typedef) | | `[std::wstring](../string/basic_string "cpp/string/basic string")` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<wchar\_t>` (typedef) | | `[std::pmr::basic\_string](../string/basic_string "cpp/string/basic string")` (C++17) | (alias template) | | `[std::pmr::string](../string/basic_string "cpp/string/basic string")` (C++17) | `[std::pmr::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char>` (typedef) | | `[std::pmr::u8string](../string/basic_string "cpp/string/basic string")` (C++20) | `[std::pmr::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char8_t>` (typedef) | | `[std::pmr::u16string](../string/basic_string "cpp/string/basic string")` (C++17) | `[std::pmr::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char16\_t>` (typedef) | | `[std::pmr::u32string](../string/basic_string "cpp/string/basic string")` (C++17) | `[std::pmr::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char32\_t>` (typedef) | | `[std::pmr::wstring](../string/basic_string "cpp/string/basic string")` (C++17) | `[std::pmr::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<wchar\_t>` (typedef) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++11) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::u8string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++20) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::u16string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++11) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::u32string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++11) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::wstring](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++11) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::pmr::string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++20) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::pmr::u8string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++20) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::pmr::u16string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++20) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::pmr::u32string](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++20) | (class template specialization) | | `[std::hash](http://en.cppreference.com/w/cpp/utility/hash)<[std::pmr::wstring](http://en.cppreference.com/w/cpp/string/basic_string)>` (C++20) | (class template specialization) | | Functions | | [operator+](../string/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<=>](../string/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)](../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)](../string/basic_string/erase2 "cpp/string/basic string/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | | Input/output | | [operator<<operator>>](../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function template) | | [getline](../string/basic_string/getline "cpp/string/basic string/getline") | read data from an I/O stream into a string (function template) | | Numeric conversions | | [stoistolstoll](../string/basic_string/stol "cpp/string/basic string/stol") (C++11)(C++11)(C++11) | converts a string to a signed integer (function) | | [stoulstoull](../string/basic_string/stoul "cpp/string/basic string/stoul") (C++11)(C++11) | converts a string to an unsigned integer (function) | | [stofstodstold](../string/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](../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](../string/basic_string/to_wstring "cpp/string/basic string/to wstring") (C++11) | converts an integral or floating point value to `wstring` (function) | | Range accesss | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | | Literals | | Defined in inline namespace `std::literals::string_literals` | | [operator""s](../string/basic_string/operator%22%22s "cpp/string/basic string/operator\"\"s") (C++14) | Converts a character array literal to `basic_string` (function) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // character traits template<class CharT> struct char_traits; template<> struct char_traits<char>; template<> struct char_traits<char8_t>; template<> struct char_traits<char16_t>; template<> struct char_traits<char32_t>; template<> struct char_traits<wchar_t>; // basic_string template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_string; template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(const basic_string<CharT, Traits, Allocator>& lhs, const basic_string<CharT, Traits, Allocator>& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(basic_string<CharT, Traits, Allocator>&& lhs, const basic_string<CharT, Traits, Allocator>& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(const basic_string<CharT, Traits, Allocator>& lhs, basic_string<CharT, Traits, Allocator>&& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(basic_string<CharT, Traits, Allocator>&& lhs, basic_string<CharT, Traits, Allocator>&& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(const CharT* lhs, const basic_string<CharT, Traits, Allocator>& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(const CharT* lhs, basic_string<CharT, Traits, Allocator>&& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(CharT lhs, const basic_string<CharT, Traits, Allocator>& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(CharT lhs, basic_string<CharT, Traits, Allocator>&& rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(const basic_string<CharT, Traits, Allocator>& lhs, const CharT* rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(basic_string<CharT, Traits, Allocator>&& lhs, const CharT* rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(const basic_string<CharT, Traits, Allocator>& lhs, CharT rhs); template<class CharT, class Traits, class Allocator> constexpr basic_string<CharT, Traits, Allocator> operator+(basic_string<CharT, Traits, Allocator>&& lhs, CharT rhs); template<class CharT, class Traits, class Allocator> constexpr bool operator==(const basic_string<CharT, Traits, Allocator>& lhs, const basic_string<CharT, Traits, Allocator>& rhs) noexcept; template<class CharT, class Traits, class Allocator> constexpr bool operator==(const basic_string<CharT, Traits, Allocator>& lhs, const CharT* rhs); template<class CharT, class Traits, class Allocator> constexpr /* see description */ operator<=>(const basic_string<CharT, Traits, Allocator>& lhs, const basic_string<CharT, Traits, Allocator>& rhs) noexcept; template<class CharT, class Traits, class Allocator> constexpr /* see description */ operator<=>(const basic_string<CharT, Traits, Allocator>& lhs, const CharT* rhs); // swap template<class CharT, class Traits, class Allocator> constexpr void swap(basic_string<CharT, Traits, Allocator>& lhs, basic_string<CharT, Traits, Allocator>& rhs) noexcept(noexcept(lhs.swap(rhs))); // inserters and extractors template<class CharT, class Traits, class Allocator> basic_istream<CharT, Traits>& operator>>(basic_istream<CharT, Traits>& is, basic_string<CharT, Traits, Allocator>& str); template<class CharT, class Traits, class Allocator> basic_ostream<CharT, Traits>& operator<<(basic_ostream<CharT, Traits>& os, const basic_string<CharT, Traits, Allocator>& str); template<class CharT, class Traits, class Allocator> basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>& is, basic_string<CharT, Traits, Allocator>& str, CharT delim); template<class CharT, class Traits, class Allocator> basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>&& is, basic_string<CharT, Traits, Allocator>& str, CharT delim); template<class CharT, class Traits, class Allocator> basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>& is, basic_string<CharT, Traits, Allocator>& str); template<class CharT, class Traits, class Allocator> basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>&& is, basic_string<CharT, Traits, Allocator>& str); // erasure template<class CharT, class Traits, class Allocator, class U> constexpr typename basic_string<CharT, Traits, Allocator>::size_type erase(basic_string<CharT, Traits, Allocator>& c, const U& value); template<class CharT, class Traits, class Allocator, class Pred> constexpr typename basic_string<CharT, Traits, Allocator>::size_type erase_if(basic_string<CharT, Traits, Allocator>& c, Pred pred); // basic_string typedef-names using string = basic_string<char>; using u8string = basic_string<char8_t>; using u16string = basic_string<char16_t>; using u32string = basic_string<char32_t>; using wstring = basic_string<wchar_t>; // numeric conversions int stoi(const string& str, size_t* idx = nullptr, int base = 10); long stol(const string& str, size_t* idx = nullptr, int base = 10); unsigned long stoul(const string& str, size_t* idx = nullptr, int base = 10); long long stoll(const string& str, size_t* idx = nullptr, int base = 10); unsigned long long stoull(const string& str, size_t* idx = nullptr, int base = 10); float stof(const string& str, size_t* idx = nullptr); double stod(const string& str, size_t* idx = nullptr); long double stold(const string& str, size_t* idx = nullptr); string to_string(int val); string to_string(unsigned val); string to_string(long val); string to_string(unsigned long val); string to_string(long long val); string to_string(unsigned long long val); string to_string(float val); string to_string(double val); string to_string(long double val); int stoi(const wstring& str, size_t* idx = nullptr, int base = 10); long stol(const wstring& str, size_t* idx = nullptr, int base = 10); unsigned long stoul(const wstring& str, size_t* idx = nullptr, int base = 10); long long stoll(const wstring& str, size_t* idx = nullptr, int base = 10); unsigned long long stoull(const wstring& str, size_t* idx = nullptr, int base = 10); float stof(const wstring& str, size_t* idx = nullptr); double stod(const wstring& str, size_t* idx = nullptr); long double stold(const wstring& str, size_t* idx = nullptr); wstring to_wstring(int val); wstring to_wstring(unsigned val); wstring to_wstring(long val); wstring to_wstring(unsigned long val); wstring to_wstring(long long val); wstring to_wstring(unsigned long long val); wstring to_wstring(float val); wstring to_wstring(double val); wstring to_wstring(long double val); namespace pmr { template<class CharT, class Traits = char_traits<CharT>> using basic_string = std::basic_string<CharT, Traits, polymorphic_allocator<CharT>>; using string = basic_string<char>; using u8string = basic_string<char8_t>; using u16string = basic_string<char16_t>; using u32string = basic_string<char32_t>; using wstring = basic_string<wchar_t>; } // hash support template<class T> struct hash; template<class A> struct hash<basic_string<char, char_traits<char>, A>>; template<class A> struct hash<basic_string<char8_t, char_traits<char8_t>, A>>; template<class A> struct hash<basic_string<char16_t, char_traits<char16_t>, A>>; template<class A> struct hash<basic_string<char32_t, char_traits<char32_t>, A>>; template<class A> struct hash<basic_string<wchar_t, char_traits<wchar_t>, A>>; inline namespace literals { inline namespace string_literals { // suffix for basic_string literals constexpr string operator""s(const char* str, size_t len); constexpr u8string operator""s(const char8_t* str, size_t len); constexpr u16string operator""s(const char16_t* str, size_t len); constexpr u32string operator""s(const char32_t* str, size_t len); constexpr wstring operator""s(const wchar_t* str, size_t len); } } } ``` #### Class template `[std::char\_traits](../string/char_traits "cpp/string/char traits")` ``` namespace std { template<> struct char_traits<char> { using char_type = char; using int_type = int; using off_type = streamoff; using pos_type = streampos; using state_type = mbstate_t; using comparison_category = strong_ordering; static constexpr void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static constexpr int compare(const char_type* s1, const char_type* s2, size_t n); static constexpr size_t length(const char_type* s); static constexpr const char_type* find(const char_type* s, size_t n, const char_type& a); static constexpr char_type* move(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* copy(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* assign(char_type* s, size_t n, char_type a); static constexpr int_type not_eof(int_type c) noexcept; static constexpr char_type to_char_type(int_type c) noexcept; static constexpr int_type to_int_type(char_type c) noexcept; static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept; static constexpr int_type eof() noexcept; }; template<> struct char_traits<char8_t> { using char_type = char8_t; using int_type = unsigned int; using off_type = streamoff; using pos_type = u8streampos; using state_type = mbstate_t; using comparison_category = strong_ordering; static constexpr void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static constexpr int compare(const char_type* s1, const char_type* s2, size_t n); static constexpr size_t length(const char_type* s); static constexpr const char_type* find(const char_type* s, size_t n, const char_type& a); static constexpr char_type* move(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* copy(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* assign(char_type* s, size_t n, char_type a); static constexpr int_type not_eof(int_type c) noexcept; static constexpr char_type to_char_type(int_type c) noexcept; static constexpr int_type to_int_type(char_type c) noexcept; static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept; static constexpr int_type eof() noexcept; }; template<> struct char_traits<char16_t> { using char_type = char16_t; using int_type = uint_least16_t; using off_type = streamoff; using pos_type = u16streampos; using state_type = mbstate_t; using comparison_category = strong_ordering; static constexpr void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static constexpr int compare(const char_type* s1, const char_type* s2, size_t n); static constexpr size_t length(const char_type* s); static constexpr const char_type* find(const char_type* s, size_t n, const char_type& a); static constexpr char_type* move(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* copy(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* assign(char_type* s, size_t n, char_type a); static constexpr int_type not_eof(int_type c) noexcept; static constexpr char_type to_char_type(int_type c) noexcept; static constexpr int_type to_int_type(char_type c) noexcept; static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept; static constexpr int_type eof() noexcept; }; template<> struct char_traits<char32_t> { using char_type = char32_t; using int_type = uint_least32_t; using off_type = streamoff; using pos_type = u32streampos; using state_type = mbstate_t; using comparison_category = strong_ordering; static constexpr void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static constexpr int compare(const char_type* s1, const char_type* s2, size_t n); static constexpr size_t length(const char_type* s); static constexpr const char_type* find(const char_type* s, size_t n, const char_type& a); static constexpr char_type* move(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* copy(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* assign(char_type* s, size_t n, char_type a); static constexpr int_type not_eof(int_type c) noexcept; static constexpr char_type to_char_type(int_type c) noexcept; static constexpr int_type to_int_type(char_type c) noexcept; static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept; static constexpr int_type eof() noexcept; }; template<> struct char_traits<wchar_t> { using char_type = wchar_t; using int_type = wint_t; using off_type = streamoff; using pos_type = wstreampos; using state_type = mbstate_t; using comparison_category = strong_ordering; static constexpr void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static constexpr int compare(const char_type* s1, const char_type* s2, size_t n); static constexpr size_t length(const char_type* s); static constexpr const char_type* find(const char_type* s, size_t n, const char_type& a); static constexpr char_type* move(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* copy(char_type* s1, const char_type* s2, size_t n); static constexpr char_type* assign(char_type* s, size_t n, char_type a); static constexpr int_type not_eof(int_type c) noexcept; static constexpr char_type to_char_type(int_type c) noexcept; static constexpr int_type to_int_type(char_type c) noexcept; static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept; static constexpr int_type eof() noexcept; }; } ``` #### Class template `[std::basic\_string](../string/basic_string "cpp/string/basic string")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>, class Allocator = allocator<CharT>> class basic_string { public: // types using traits_type = Traits; using value_type = CharT; using allocator_type = Allocator; using size_type = typename allocator_traits<Allocator>::size_type; using difference_type = typename allocator_traits<Allocator>::difference_type; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; static constexpr size_type npos = size_type(-1); // construct/copy/destroy constexpr basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { } constexpr explicit basic_string(const Allocator& a) noexcept; constexpr basic_string(const basic_string& str); constexpr basic_string(basic_string&& str) noexcept; constexpr basic_string(const basic_string& str, size_type pos, const Allocator& a = Allocator()); constexpr basic_string(const basic_string& str, size_type pos, size_type n, const Allocator& a = Allocator()); constexpr basic_string(basic_string&& str, size_type pos, const Allocator& a = Allocator()); constexpr basic_string(basic_string&& str, size_type pos, size_type n, const Allocator& a = Allocator()); template<class T> constexpr basic_string(const T& t, size_type pos, size_type n, const Allocator& a = Allocator()); template<class T> constexpr explicit basic_string(const T& t, const Allocator& a = Allocator()); constexpr basic_string(const CharT* s, size_type n, const Allocator& a = Allocator()); constexpr basic_string(const CharT* s, const Allocator& a = Allocator()); basic_string(nullptr_t) = delete; constexpr basic_string(size_type n, CharT c, const Allocator& a = Allocator()); template<class InputIt> constexpr basic_string(InputIt begin, InputIt end, const Allocator& a = Allocator()); template<__container_compatible_range<CharT> R> constexpr basic_string(from_range_t, R&& rg, const Allocator& a = Allocator()); constexpr basic_string(initializer_list<CharT>, const Allocator& = Allocator()); constexpr basic_string(const basic_string&, const Allocator&); constexpr basic_string(basic_string&&, const Allocator&); constexpr ~basic_string(); constexpr basic_string& operator=(const basic_string& str); constexpr basic_string& operator=(basic_string&& str) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value); template<class T> constexpr basic_string& operator=(const T& t); constexpr basic_string& operator=(const CharT* s); basic_string& operator=(nullptr_t) = delete; constexpr basic_string& operator=(CharT c); constexpr basic_string& operator=(initializer_list<CharT>); // iterators constexpr iterator begin() noexcept; constexpr const_iterator begin() const noexcept; constexpr iterator end() noexcept; constexpr const_iterator end() const noexcept; constexpr reverse_iterator rbegin() noexcept; constexpr const_reverse_iterator rbegin() const noexcept; constexpr reverse_iterator rend() noexcept; constexpr const_reverse_iterator rend() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept; constexpr const_reverse_iterator crend() const noexcept; // capacity constexpr size_type size() const noexcept; constexpr size_type length() const noexcept; constexpr size_type max_size() const noexcept; constexpr void resize(size_type n, CharT c); constexpr void resize(size_type n); template<class Operation> constexpr void resize_and_overwrite(size_type n, Operation op); constexpr size_type capacity() const noexcept; constexpr void reserve(size_type res_arg); constexpr void shrink_to_fit(); constexpr void clear() noexcept; [[nodiscard]] constexpr bool empty() const noexcept; // element access constexpr const_reference operator[](size_type pos) const; constexpr reference operator[](size_type pos); constexpr const_reference at(size_type n) const; constexpr reference at(size_type n); constexpr const CharT& front() const; constexpr CharT& front(); constexpr const CharT& back() const; constexpr CharT& back(); // modifiers constexpr basic_string& operator+=(const basic_string& str); template<class T> constexpr basic_string& operator+=(const T& t); constexpr basic_string& operator+=(const CharT* s); constexpr basic_string& operator+=(CharT c); constexpr basic_string& operator+=(initializer_list<CharT>); constexpr basic_string& append(const basic_string& str); constexpr basic_string& append(const basic_string& str, size_type pos, size_type n = npos); template<class T> constexpr basic_string& append(const T& t); template<class T> constexpr basic_string& append(const T& t, size_type pos, size_type n = npos); constexpr basic_string& append(const CharT* s, size_type n); constexpr basic_string& append(const CharT* s); constexpr basic_string& append(size_type n, CharT c); template<class InputIt> constexpr basic_string& append(InputIt first, InputIt last); template<__container_compatible_range<CharT> R> constexpr basic_string& append_range(R&& rg); constexpr basic_string& append(initializer_list<CharT>); constexpr void push_back(CharT c); constexpr basic_string& assign(const basic_string& str); constexpr basic_string& assign(basic_string&& str) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value); constexpr basic_string& assign(const basic_string& str, size_type pos, size_type n = npos); template<class T> constexpr basic_string& assign(const T& t); template<class T> constexpr basic_string& assign(const T& t, size_type pos, size_type n = npos); constexpr basic_string& assign(const CharT* s, size_type n); constexpr basic_string& assign(const CharT* s); constexpr basic_string& assign(size_type n, CharT c); template<class InputIt> constexpr basic_string& assign(InputIt first, InputIt last); template<__container_compatible_range<CharT> R> constexpr basic_string& assign_range(R&& rg); constexpr basic_string& assign(initializer_list<CharT>); constexpr basic_string& insert(size_type pos, const basic_string& str); constexpr basic_string& insert(size_type pos1, const basic_string& str, size_type pos2, size_type n = npos); template<class T> constexpr basic_string& insert(size_type pos, const T& t); template<class T> constexpr basic_string& insert(size_type pos1, const T& t, size_type pos2, size_type n = npos); constexpr basic_string& insert(size_type pos, const CharT* s, size_type n); constexpr basic_string& insert(size_type pos, const CharT* s); constexpr basic_string& insert(size_type pos, size_type n, CharT c); constexpr iterator insert(const_iterator p, CharT c); constexpr iterator insert(const_iterator p, size_type n, CharT c); template<class InputIt> constexpr iterator insert(const_iterator p, InputIt first, InputIt last); template<__container_compatible_range<CharT> R> constexpr iterator insert_range(const_iterator p, R&& rg); constexpr iterator insert(const_iterator p, initializer_list<CharT>); constexpr basic_string& erase(size_type pos = 0, size_type n = npos); constexpr iterator erase(const_iterator p); constexpr iterator erase(const_iterator first, const_iterator last); constexpr void pop_back(); constexpr basic_string& replace(size_type pos1, size_type n1, const basic_string& str); constexpr basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2 = npos); template<class T> constexpr basic_string& replace(size_type pos1, size_type n1, const T& t); template<class T> constexpr basic_string& replace(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos); constexpr basic_string& replace(size_type pos, size_type n1, const CharT* s, size_type n2); constexpr basic_string& replace(size_type pos, size_type n1, const CharT* s); constexpr basic_string& replace(size_type pos, size_type n1, size_type n2, CharT c); constexpr basic_string& replace(const_iterator i1, const_iterator i2, const basic_string& str); template<class T> constexpr basic_string& replace(const_iterator i1, const_iterator i2, const T& t); constexpr basic_string& replace(const_iterator i1, const_iterator i2, const CharT* s, size_type n); constexpr basic_string& replace(const_iterator i1, const_iterator i2, const CharT* s); constexpr basic_string& replace(const_iterator i1, const_iterator i2, size_type n, CharT c); template<class InputIt> constexpr basic_string& replace(const_iterator i1, const_iterator i2, InputIt j1, InputIt j2); template<__container_compatible_range<CharT> R> constexpr basic_string& replace_with_range(const_iterator i1, const_iterator i2, R&& rg); constexpr basic_string& replace(const_iterator, const_iterator, initializer_list<CharT>); constexpr size_type copy(CharT* s, size_type n, size_type pos = 0) const; constexpr void swap(basic_string& str) noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value || allocator_traits<Allocator>::is_always_equal::value); // string operations constexpr const CharT* c_str() const noexcept; constexpr const CharT* data() const noexcept; constexpr CharT* data() noexcept; constexpr operator basic_string_view<CharT, Traits>() const noexcept; constexpr allocator_type get_allocator() const noexcept; template<class T> constexpr size_type find(const T& t, size_type pos = 0) const noexcept(/* see description */); constexpr size_type find(const basic_string& str, size_type pos = 0) const noexcept; constexpr size_type find(const CharT* s, size_type pos, size_type n) const; constexpr size_type find(const CharT* s, size_type pos = 0) const; constexpr size_type find(CharT c, size_type pos = 0) const noexcept; template<class T> constexpr size_type rfind(const T& t, size_type pos = npos) const noexcept(/* see description */); constexpr size_type rfind(const basic_string& str, size_type pos = npos) const noexcept; constexpr size_type rfind(const CharT* s, size_type pos, size_type n) const; constexpr size_type rfind(const CharT* s, size_type pos = npos) const; constexpr size_type rfind(CharT c, size_type pos = npos) const noexcept; template<class T> constexpr size_type find_first_of(const T& t, size_type pos = 0) const noexcept(/* see description */); constexpr size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept; constexpr size_type find_first_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_first_of(const CharT* s, size_type pos = 0) const; constexpr size_type find_first_of(CharT c, size_type pos = 0) const noexcept; template<class T> constexpr size_type find_last_of(const T& t, size_type pos = npos) const noexcept(/* see description */); constexpr size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept; constexpr size_type find_last_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_last_of(const CharT* s, size_type pos = npos) const; constexpr size_type find_last_of(CharT c, size_type pos = npos) const noexcept; template<class T> constexpr size_type find_first_not_of(const T& t, size_type pos = 0) const noexcept(/* see description */); constexpr size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept; constexpr size_type find_first_not_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_first_not_of(const CharT* s, size_type pos = 0) const; constexpr size_type find_first_not_of(CharT c, size_type pos = 0) const noexcept; template<class T> constexpr size_type find_last_not_of(const T& t, size_type pos = npos) const noexcept(/* see description */); constexpr size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept; constexpr size_type find_last_not_of(const CharT* s, size_type pos, size_type n) const; constexpr size_type find_last_not_of(const CharT* s, size_type pos = npos) const; constexpr size_type find_last_not_of(CharT c, size_type pos = npos) const noexcept; constexpr basic_string substr(size_type pos = 0, size_type n = npos) const &; constexpr basic_string substr(size_type pos = 0, size_type n = npos) &&; template<class T> constexpr int compare(const T& t) const noexcept(/* see description */); template<class T> constexpr int compare(size_type pos1, size_type n1, const T& t) const; template<class T> constexpr int compare(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos) const; constexpr int compare(const basic_string& str) const noexcept; constexpr int compare(size_type pos1, size_type n1, const basic_string& str) const; constexpr int compare(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2 = npos) const; constexpr int compare(const CharT* s) const; constexpr int compare(size_type pos1, size_type n1, const CharT* s) const; constexpr int compare(size_type pos1, size_type n1, const CharT* s, size_type n2) const; constexpr bool starts_with(basic_string_view<CharT, Traits> x) const noexcept; constexpr bool starts_with(CharT x) const noexcept; constexpr bool starts_with(const CharT* x) const; constexpr bool ends_with(basic_string_view<CharT, Traits> x) const noexcept; constexpr bool ends_with(CharT x) const noexcept; constexpr bool ends_with(const CharT* x) const; constexpr bool contains(basic_string_view<CharT, Traits> x) const noexcept; constexpr bool contains(CharT x) const noexcept; constexpr bool contains(const CharT* x) const; }; template<class InputIt, class Allocator = allocator<typename iterator_traits<InputIt>::value_type>> basic_string(InputIt, InputIt, Allocator = Allocator()) -> basic_string<typename iterator_traits<InputIt>::value_type, char_traits<typename iterator_traits<InputIt>::value_type>, Allocator>; template<ranges::input_range R, class Allocator = allocator<ranges::range_value_t<R>>> basic_string(from_range_t, R&&, Allocator = Allocator()) -> basic_string<ranges::range_value_t<R>, char_traits<ranges::range_value_t<R>>, Allocator>; template<class CharT, class Traits, class Allocator = allocator<CharT>> explicit basic_string(basic_string_view<CharT, Traits>, const Allocator& = Allocator()) -> basic_string<CharT, Traits, Allocator>; template<class CharT, class Traits, class Allocator = allocator<CharT>> basic_string(basic_string_view<CharT, Traits>, typename /* see description */::size_type, typename /* see description */::size_type, const Allocator& = Allocator()) -> basic_string<CharT, Traits, Allocator>; } ```
programming_docs
cpp Standard library header <unordered_set> (C++11) Standard library header <unordered\_set> (C++11) ================================================ This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [unordered\_set](../container/unordered_set "cpp/container/unordered set") (C++11) | collection of unique keys, hashed by keys (class template) | | [unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset") (C++11) | collection of keys, hashed by keys (class template) | | Functions | | [operator==operator!=](../container/unordered_set/operator_cmp "cpp/container/unordered set/operator cmp") (removed in C++20) | compares the values in the unordered\_set (function template) | | [std::swap(std::unordered\_set)](../container/unordered_set/swap2 "cpp/container/unordered set/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_set)](../container/unordered_set/erase_if "cpp/container/unordered set/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | [operator==operator!=](../container/unordered_multiset/operator_cmp "cpp/container/unordered multiset/operator cmp") (removed in C++20) | compares the values in the unordered\_multiset (function template) | | [std::swap(std::unordered\_multiset)](../container/unordered_multiset/swap2 "cpp/container/unordered multiset/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_multiset)](../container/unordered_multiset/erase_if "cpp/container/unordered multiset/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template unordered_set template<class Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key>> class unordered_set; // class template unordered_multiset template<class Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key>> class unordered_multiset; template<class Key, class Hash, class Pred, class Alloc> bool operator==(const unordered_set<Key, Hash, Pred, Alloc>& a, const unordered_set<Key, Hash, Pred, Alloc>& b); template<class Key, class Hash, class Pred, class Alloc> bool operator==(const unordered_multiset<Key, Hash, Pred, Alloc>& a, const unordered_multiset<Key, Hash, Pred, Alloc>& b); template<class Key, class Hash, class Pred, class Alloc> void swap(unordered_set<Key, Hash, Pred, Alloc>& x, unordered_set<Key, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); template<class Key, class Hash, class Pred, class Alloc> void swap(unordered_multiset<Key, Hash, Pred, Alloc>& x, unordered_multiset<Key, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); template<class K, class H, class P, class A, class Predicate> typename unordered_set<K, H, P, A>::size_type erase_if(unordered_set<K, H, P, A>& c, Predicate pred); template<class K, class H, class P, class A, class Predicate> typename unordered_multiset<K, H, P, A>::size_type erase_if(unordered_multiset<K, H, P, A>& c, Predicate pred); namespace pmr { template<class Key, class Hash = hash<Key>, class Pred = equal_to<Key>> using unordered_set = std::unordered_set<Key, Hash, Pred, polymorphic_allocator<Key>>; template<class Key, class Hash = hash<Key>, class Pred = equal_to<Key>> using unordered_multiset = std::unordered_multiset<Key, Hash, Pred, polymorphic_allocator<Key>>; } } ``` #### Class template `[std::unordered\_set](../container/unordered_set "cpp/container/unordered set")` ``` namespace std { template<class Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Allocator = allocator<Key>> class unordered_set { public: // types using key_type = Key; using value_type = Key; using hasher = Hash; using key_equal = Pred; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using local_iterator = /* implementation-defined */; using const_local_iterator = /* implementation-defined */; using node_type = /* unspecified */; using insert_return_type = /*insert-return-type*/<iterator, node_type>; // construct/copy/destroy unordered_set(); explicit unordered_set(size_type n, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template<class InputIt> unordered_set(InputIt f, InputIt l, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_set(const unordered_set&); unordered_set(unordered_set&&); explicit unordered_set(const Allocator&); unordered_set(const unordered_set&, const Allocator&); unordered_set(unordered_set&&, const Allocator&); unordered_set(initializer_list<value_type> il, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_set(size_type n, const allocator_type& a) : unordered_set(n, hasher(), key_equal(), a) { } unordered_set(size_type n, const hasher& hf, const allocator_type& a) : unordered_set(n, hf, key_equal(), a) { } template<class InputIt> unordered_set(InputIt f, InputIt l, size_type n, const allocator_type& a) : unordered_set(f, l, n, hasher(), key_equal(), a) { } template<class InputIt> unordered_set(InputIt f, InputIt l, size_type n, const hasher& hf, const allocator_type& a) : unordered_set(f, l, n, hf, key_equal(), a) { } unordered_set(initializer_list<value_type> il, size_type n, const allocator_type& a) : unordered_set(il, n, hasher(), key_equal(), a) { } unordered_set(initializer_list<value_type> il, size_type n, const hasher& hf, const allocator_type& a) : unordered_set(il, n, hf, key_equal(), a) { } ~unordered_set(); unordered_set& operator=(const unordered_set&); unordered_set& operator=(unordered_set&&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Hash> && is_nothrow_move_assignable_v<Pred>); unordered_set& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> pair<iterator, bool> emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); pair<iterator, bool> insert(const value_type& obj); pair<iterator, bool> insert(value_type&& obj); iterator insert(const_iterator hint, const value_type& obj); iterator insert(const_iterator hint, value_type&& obj); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); insert_return_type insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& k); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(unordered_set&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Hash> && is_nothrow_swappable_v<Pred>); void clear() noexcept; template<class H2, class P2> void merge(unordered_set<Key, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_set<Key, H2, P2, Allocator>&& source); template<class H2, class P2> void merge(unordered_multiset<Key, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_multiset<Key, H2, P2, Allocator>&& source); // observers hasher hash_function() const; key_equal key_eq() const; // set operations iterator find(const key_type& k); const_iterator find(const key_type& k) const; template<class K> iterator find(const K& k); template<class K> const_iterator find(const K& k) const; size_type count(const key_type& k) const; template<class K> size_type count(const K& k) const; bool contains(const key_type& k) const; template<class K> bool contains(const K& k) const; pair<iterator, iterator> equal_range(const key_type& k); pair<const_iterator, const_iterator> equal_range(const key_type& k) const; template<class K> pair<iterator, iterator> equal_range(const K& k); template<class K> pair<const_iterator, const_iterator> equal_range(const K& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template<class InputIt, class Hash = hash</*iter-value-type*/<InputIt>>, class Pred = equal_to</*iter-value-type*/<InputIt>>, class Allocator = allocator</*iter-value-type*/<InputIt>>> unordered_set(InputIt, InputIt, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_set</*iter-value-type*/<InputIt>, Hash, Pred, Allocator>; template<class T, class Hash = hash<T>, class Pred = equal_to<T>, class Allocator = allocator<T>> unordered_set(initializer_list<T>, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_set<T, Hash, Pred, Allocator>; template<class InputIt, class Allocator> unordered_set(InputIt, InputIt, typename /* see description */::size_type, Allocator) -> unordered_set</*iter-value-type*/<InputIt>, hash</*iter-value-type*/<InputIt>>, equal_to</*iter-value-type*/<InputIt>>, Allocator>; template<class InputIt, class Hash, class Allocator> unordered_set(InputIt, InputIt, typename /* see description */::size_type, Hash, Allocator) -> unordered_set</*iter-value-type*/<InputIt>, Hash, equal_to</*iter-value-type*/<InputIt>>, Allocator>; template<class T, class Allocator> unordered_set(initializer_list<T>, typename /* see description */::size_type, Allocator) -> unordered_set<T, hash<T>, equal_to<T>, Allocator>; template<class T, class Hash, class Allocator> unordered_set(initializer_list<T>, typename /* see description */::size_type, Hash, Allocator) -> unordered_set<T, Hash, equal_to<T>, Allocator>; // swap template<class Key, class Hash, class Pred, class Alloc> void swap(unordered_set<Key, Hash, Pred, Alloc>& x, unordered_set<Key, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); } ``` #### Class template `[std::unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset")` ``` namespace std { template<class Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Allocator = allocator<Key>> class unordered_multiset { public: // types using key_type = Key; using value_type = Key; using hasher = Hash; using key_equal = Pred; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using local_iterator = /* implementation-defined */; using const_local_iterator = /* implementation-defined */; using node_type = /* unspecified */; // construct/copy/destroy unordered_multiset(); explicit unordered_multiset(size_type n, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template<class InputIt> unordered_multiset(InputIt f, InputIt l, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_multiset(const unordered_multiset&); unordered_multiset(unordered_multiset&&); explicit unordered_multiset(const Allocator&); unordered_multiset(const unordered_multiset&, const Allocator&); unordered_multiset(unordered_multiset&&, const Allocator&); unordered_multiset(initializer_list<value_type> il, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_multiset(size_type n, const allocator_type& a) : unordered_multiset(n, hasher(), key_equal(), a) { } unordered_multiset(size_type n, const hasher& hf, const allocator_type& a) : unordered_multiset(n, hf, key_equal(), a) { } template<class InputIt> unordered_multiset(InputIt f, InputIt l, size_type n, const allocator_type& a) : unordered_multiset(f, l, n, hasher(), key_equal(), a) { } template<class InputIt> unordered_multiset(InputIt f, InputIt l, size_type n, const hasher& hf, const allocator_type& a) : unordered_multiset(f, l, n, hf, key_equal(), a) { } unordered_multiset(initializer_list<value_type> il, size_type n, const allocator_type& a) : unordered_multiset(il, n, hasher(), key_equal(), a) { } unordered_multiset(initializer_list<value_type> il, size_type n, const hasher& hf, const allocator_type& a) : unordered_multiset(il, n, hf, key_equal(), a) { } ~unordered_multiset(); unordered_multiset& operator=(const unordered_multiset&); unordered_multiset& operator=(unordered_multiset&&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Hash> && is_nothrow_move_assignable_v<Pred>); unordered_multiset& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> iterator emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& obj); iterator insert(value_type&& obj); iterator insert(const_iterator hint, const value_type& obj); iterator insert(const_iterator hint, value_type&& obj); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); iterator insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& k); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(unordered_multiset&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Hash> && is_nothrow_swappable_v<Pred>); void clear() noexcept; template<class H2, class P2> void merge(unordered_multiset<Key, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_multiset<Key, H2, P2, Allocator>&& source); template<class H2, class P2> void merge(unordered_set<Key, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_set<Key, H2, P2, Allocator>&& source); // observers hasher hash_function() const; key_equal key_eq() const; // set operations iterator find(const key_type& k); const_iterator find(const key_type& k) const; template<class K> iterator find(const K& k); template<class K> const_iterator find(const K& k) const; size_type count(const key_type& k) const; template<class K> size_type count(const K& k) const; bool contains(const key_type& k) const; template<class K> bool contains(const K& k) const; pair<iterator, iterator> equal_range(const key_type& k); pair<const_iterator, const_iterator> equal_range(const key_type& k) const; template<class K> pair<iterator, iterator> equal_range(const K& k); template<class K> pair<const_iterator, const_iterator> equal_range(const K& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template<class InputIt, class Hash = hash</*iter-value-type*/<InputIt>>, class Pred = equal_to</*iter-value-type*/<InputIt>>, class Allocator = allocator</*iter-value-type*/<InputIt>>> unordered_multiset(InputIt, InputIt, /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_multiset</*iter-value-type*/<InputIt>, Hash, Pred, Allocator>; template<class T, class Hash = hash<T>, class Pred = equal_to<T>, class Allocator = allocator<T>> unordered_multiset(initializer_list<T>, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_multiset<T, Hash, Pred, Allocator>; template<class InputIt, class Allocator> unordered_multiset(InputIt, InputIt, typename /* see description */::size_type, Allocator) -> unordered_multiset</*iter-value-type*/<InputIt>, hash</*iter-value-type*/<InputIt>>, equal_to</*iter-value-type*/<InputIt>>, Allocator>; template<class InputIt, class Hash, class Allocator> unordered_multiset(InputIt, InputIt, typename /* see description */::size_type, Hash, Allocator) -> unordered_multiset</*iter-value-type*/<InputIt>, Hash, equal_to</*iter-value-type*/<InputIt>>, Allocator>; template<class T, class Allocator> unordered_multiset(initializer_list<T>, typename /* see description */::size_type, Allocator) -> unordered_multiset<T, hash<T>, equal_to<T>, Allocator>; template<class T, class Hash, class Allocator> unordered_multiset(initializer_list<T>, typename /* see description */::size_type, Hash, Allocator) -> unordered_multiset<T, Hash, equal_to<T>, Allocator>; // swap template<class Key, class Hash, class Pred, class Alloc> void swap(unordered_multiset<Key, Hash, Pred, Alloc>& x, unordered_multiset<Key, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); } ```
programming_docs
cpp Standard library header <type_traits> (C++11) Standard library header <type\_traits> (C++11) ============================================== This header is part of the [metaprogramming](../meta "cpp/meta") library. | | | --- | | Classes | | Helper Classes | | [integral\_constantbool\_constant](../types/integral_constant "cpp/types/integral constant") (C++11)(C++17) | compile-time constant of specified type with specified value (class template) | | `true_type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, true>` | | `false_type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, false>` | | Primary type categories | | [is\_void](../types/is_void "cpp/types/is void") (C++11) | checks if a type is `void` (class template) | | [is\_null\_pointer](../types/is_null_pointer "cpp/types/is null pointer") (C++14) | checks if a type is `[std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)` (class template) | | [is\_integral](../types/is_integral "cpp/types/is integral") (C++11) | checks if a type is an integral type (class template) | | [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) | | [is\_array](../types/is_array "cpp/types/is array") (C++11) | checks if a type is an array type (class template) | | [is\_enum](../types/is_enum "cpp/types/is enum") (C++11) | checks if a type is an enumeration type (class template) | | [is\_union](../types/is_union "cpp/types/is union") (C++11) | checks if a type is an union type (class template) | | [is\_class](../types/is_class "cpp/types/is class") (C++11) | checks if a type is a non-union class type (class template) | | [is\_function](../types/is_function "cpp/types/is function") (C++11) | checks if a type is a function type (class template) | | [is\_pointer](../types/is_pointer "cpp/types/is pointer") (C++11) | checks if a type is a pointer type (class template) | | [is\_lvalue\_reference](../types/is_lvalue_reference "cpp/types/is lvalue reference") (C++11) | checks if a type is a *lvalue reference* (class template) | | [is\_rvalue\_reference](../types/is_rvalue_reference "cpp/types/is rvalue reference") (C++11) | checks if a type is a *rvalue reference* (class template) | | [is\_member\_object\_pointer](../types/is_member_object_pointer "cpp/types/is member object pointer") (C++11) | checks if a type is a pointer to a non-static member object (class template) | | [is\_member\_function\_pointer](../types/is_member_function_pointer "cpp/types/is member function pointer") (C++11) | checks if a type is a pointer to a non-static member function (class template) | | Composite type categories | | [is\_fundamental](../types/is_fundamental "cpp/types/is fundamental") (C++11) | checks if a type is a fundamental type (class template) | | [is\_arithmetic](../types/is_arithmetic "cpp/types/is arithmetic") (C++11) | checks if a type is an arithmetic type (class template) | | [is\_scalar](../types/is_scalar "cpp/types/is scalar") (C++11) | checks if a type is a scalar type (class template) | | [is\_object](../types/is_object "cpp/types/is object") (C++11) | checks if a type is an object type (class template) | | [is\_compound](../types/is_compound "cpp/types/is compound") (C++11) | checks if a type is a compound type (class template) | | [is\_reference](../types/is_reference "cpp/types/is reference") (C++11) | checks if a type is either a *lvalue reference* or *rvalue reference* (class template) | | [is\_member\_pointer](../types/is_member_pointer "cpp/types/is member pointer") (C++11) | checks if a type is a pointer to an non-static member function or object (class template) | | Type properties | | [is\_const](../types/is_const "cpp/types/is const") (C++11) | checks if a type is const-qualified (class template) | | [is\_volatile](../types/is_volatile "cpp/types/is volatile") (C++11) | checks if a type is volatile-qualified (class template) | | [is\_trivial](../types/is_trivial "cpp/types/is trivial") (C++11) | checks if a type is trivial (class template) | | [is\_trivially\_copyable](../types/is_trivially_copyable "cpp/types/is trivially copyable") (C++11) | checks if a type is trivially copyable (class template) | | [is\_standard\_layout](../types/is_standard_layout "cpp/types/is standard layout") (C++11) | checks if a type is a [standard-layout](../language/data_members#Standard_layout "cpp/language/data members") type (class template) | | [is\_pod](../types/is_pod "cpp/types/is pod") (C++11)(deprecated in C++20) | checks if a type is a plain-old data (POD) type (class template) | | [is\_literal\_type](../types/is_literal_type "cpp/types/is literal type") (C++11)(deprecated in C++17)(removed in C++20) | checks if a type is a literal type (class template) | | [has\_unique\_object\_representations](../types/has_unique_object_representations "cpp/types/has unique object representations") (C++17) | checks if every bit in the type's object representation contributes to its value (class template) | | [is\_empty](../types/is_empty "cpp/types/is empty") (C++11) | checks if a type is a class (but not union) type and has no non-static data members (class template) | | [is\_polymorphic](../types/is_polymorphic "cpp/types/is polymorphic") (C++11) | checks if a type is a polymorphic class type (class template) | | [is\_abstract](../types/is_abstract "cpp/types/is abstract") (C++11) | checks if a type is an abstract class type (class template) | | [is\_final](../types/is_final "cpp/types/is final") (C++14) | checks if a type is a final class type (class template) | | [is\_aggregate](../types/is_aggregate "cpp/types/is aggregate") (C++17) | checks if a type is an aggregate 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) | | [is\_unsigned](../types/is_unsigned "cpp/types/is unsigned") (C++11) | checks if a type is an unsigned arithmetic type (class template) | | [is\_bounded\_array](../types/is_bounded_array "cpp/types/is bounded array") (C++20) | checks if a type is an array type of known bound (class template) | | [is\_unbounded\_array](../types/is_unbounded_array "cpp/types/is unbounded array") (C++20) | checks if a type is an array type of unknown bound (class template) | | [is\_scoped\_enum](../types/is_scoped_enum "cpp/types/is scoped enum") (C++23) | checks if a type is a scoped enumeration type (class template) | | | | --- | | Supported operations | | [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) | | [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) | | [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) | | [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) | | [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) | | [is\_copy\_assignableis\_trivially\_copy\_assignableis\_nothrow\_copy\_assignable](../types/is_copy_assignable "cpp/types/is copy assignable") (C++11)(C++11)(C++11) | checks if a type has a copy assignment operator (class template) | | [is\_move\_assignableis\_trivially\_move\_assignableis\_nothrow\_move\_assignable](../types/is_move_assignable "cpp/types/is move assignable") (C++11)(C++11)(C++11) | checks if a type has a move assignment operator (class template) | | [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) | | [has\_virtual\_destructor](../types/has_virtual_destructor "cpp/types/has virtual destructor") (C++11) | checks if a type has a virtual destructor (class template) | | [is\_swappable\_withis\_swappableis\_nothrow\_swappable\_withis\_nothrow\_swappable](../types/is_swappable "cpp/types/is swappable") (C++17)(C++17)(C++17)(C++17) | checks if objects of a type can be swapped with objects of same or different type (class template) | | | | --- | | Property queries | | [alignment\_of](../types/alignment_of "cpp/types/alignment of") (C++11) | obtains the type's alignment requirements (class template) | | [rank](../types/rank "cpp/types/rank") (C++11) | obtains the number of dimensions of an array type (class template) | | [extent](../types/extent "cpp/types/extent") (C++11) | obtains the size of an array type along a specified dimension (class template) | | | | --- | | Type relationships | | [is\_same](../types/is_same "cpp/types/is same") (C++11) | checks if two types are the same (class template) | | [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) | | [is\_layout\_compatible](../types/is_layout_compatible "cpp/types/is layout compatible") (C++20) | checks if two types are [*layout-compatible*](../language/data_members#Standard_layout "cpp/language/data members") (class template) | | [is\_pointer\_interconvertible\_base\_of](../types/is_pointer_interconvertible_base_of "cpp/types/is pointer interconvertible base of") (C++20) | checks if a type is a *pointer-interconvertible* (initial) base of another type (class template) | | [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) | | Const-volatility specifiers | | [remove\_cvremove\_constremove\_volatile](../types/remove_cv "cpp/types/remove cv") (C++11)(C++11)(C++11) | removes `const` or/and `volatile` specifiers from the given type (class template) | | [add\_cvadd\_constadd\_volatile](../types/add_cv "cpp/types/add cv") (C++11)(C++11)(C++11) | adds `const` or/and `volatile` specifiers to the given type (class template) | | References | | [remove\_reference](../types/remove_reference "cpp/types/remove reference") (C++11) | removes a reference from the given type (class template) | | [add\_lvalue\_referenceadd\_rvalue\_reference](../types/add_reference "cpp/types/add reference") (C++11)(C++11) | adds a *lvalue* or *rvalue* reference to the given type (class template) | | Pointers | | [remove\_pointer](../types/remove_pointer "cpp/types/remove pointer") (C++11) | removes a pointer from the given type (class template) | | [add\_pointer](../types/add_pointer "cpp/types/add pointer") (C++11) | adds a pointer to the given type (class template) | | Sign modifiers | | [make\_signed](../types/make_signed "cpp/types/make signed") (C++11) | makes the given integral type signed (class template) | | [make\_unsigned](../types/make_unsigned "cpp/types/make unsigned") (C++11) | makes the given integral type unsigned (class template) | | Arrays | | [remove\_extent](../types/remove_extent "cpp/types/remove extent") (C++11) | removes one extent from the given array type (class template) | | [remove\_all\_extents](../types/remove_all_extents "cpp/types/remove all extents") (C++11) | removes all extents from the given array type (class template) | | Miscellaneous transformations | | [aligned\_storage](../types/aligned_storage "cpp/types/aligned storage") (C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template) | | [aligned\_union](../types/aligned_union "cpp/types/aligned union") (C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for all given types (class template) | | [decay](../types/decay "cpp/types/decay") (C++11) | applies type transformations as when passing a function argument by value (class template) | | [remove\_cvref](../types/remove_cvref "cpp/types/remove cvref") (C++20) | combines `[std::remove\_cv](../types/remove_cv "cpp/types/remove cv")` and `[std::remove\_reference](../types/remove_reference "cpp/types/remove reference")` (class template) | | [enable\_if](../types/enable_if "cpp/types/enable if") (C++11) | conditionally [removes](../language/sfinae "cpp/language/sfinae") a function overload or template specialization from overload resolution (class template) | | [conditional](../types/conditional "cpp/types/conditional") (C++11) | chooses one type or another based on compile-time boolean (class template) | | [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) | | [underlying\_type](../types/underlying_type "cpp/types/underlying type") (C++11) | obtains the underlying integer type for a given enumeration type (class template) | | [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) | | [void\_t](../types/void_t "cpp/types/void t") (C++17) | void variadic alias template (alias template) | | [type\_identity](../types/type_identity "cpp/types/type identity") (C++20) | returns the type argument unchanged (class template) | | Operations on traits | | [conjunction](../types/conjunction "cpp/types/conjunction") (C++17) | variadic logical AND metafunction (class template) | | [disjunction](../types/disjunction "cpp/types/disjunction") (C++17) | variadic logical OR metafunction (class template) | | [negation](../types/negation "cpp/types/negation") (C++17) | logical NOT metafunction (class template) | | Functions | | Member relationships | | [is\_pointer\_interconvertible\_with\_class](../types/is_pointer_interconvertible_with_class "cpp/types/is pointer interconvertible with class") (C++20) | checks if objects of a type are pointer-interconvertible with the specified subobject of that type (function template) | | [is\_corresponding\_member](../types/is_corresponding_member "cpp/types/is corresponding member") (C++20) | checks if two specified members correspond to each other in the common initial subsequence of two specified types (function template) | | Constant evaluation context | | [is\_constant\_evaluated](../types/is_constant_evaluated "cpp/types/is constant evaluated") (C++20) | detects whether the call occurs within a constant-evaluated context (function) | ### Synopsis ``` namespace std { // helper class template<class T, T v> struct integral_constant; template<bool B> using bool_constant = integral_constant<bool, B>; using true_type = bool_constant<true>; using false_type = bool_constant<false>; // primary type categories template<class T> struct is_void; template<class T> struct is_null_pointer; template<class T> struct is_integral; template<class T> struct is_floating_point; template<class T> struct is_array; template<class T> struct is_pointer; template<class T> struct is_lvalue_reference; template<class T> struct is_rvalue_reference; template<class T> struct is_member_object_pointer; template<class T> struct is_member_function_pointer; template<class T> struct is_enum; template<class T> struct is_union; template<class T> struct is_class; template<class T> struct is_function; // composite type categories template<class T> struct is_reference; template<class T> struct is_arithmetic; template<class T> struct is_fundamental; template<class T> struct is_object; template<class T> struct is_scalar; template<class T> struct is_compound; template<class T> struct is_member_pointer; // type properties template<class T> struct is_const; template<class T> struct is_volatile; template<class T> struct is_trivial; template<class T> struct is_trivially_copyable; template<class T> struct is_standard_layout; template<class T> struct is_empty; template<class T> struct is_polymorphic; template<class T> struct is_abstract; template<class T> struct is_final; template<class T> struct is_aggregate; template<class T> struct is_signed; template<class T> struct is_unsigned; template<class T> struct is_bounded_array; template<class T> struct is_unbounded_array; template<class T> struct is_scoped_enum; template<class T, class... Args> struct is_constructible; template<class T> struct is_default_constructible; template<class T> struct is_copy_constructible; template<class T> struct is_move_constructible; template<class T, class U> struct is_assignable; template<class T> struct is_copy_assignable; template<class T> struct is_move_assignable; template<class T, class U> struct is_swappable_with; template<class T> struct is_swappable; template<class T> struct is_destructible; template<class T, class... Args> struct is_trivially_constructible; template<class T> struct is_trivially_default_constructible; template<class T> struct is_trivially_copy_constructible; template<class T> struct is_trivially_move_constructible; template<class T, class U> struct is_trivially_assignable; template<class T> struct is_trivially_copy_assignable; template<class T> struct is_trivially_move_assignable; template<class T> struct is_trivially_destructible; template<class T, class... Args> struct is_nothrow_constructible; template<class T> struct is_nothrow_default_constructible; template<class T> struct is_nothrow_copy_constructible; template<class T> struct is_nothrow_move_constructible; template<class T, class U> struct is_nothrow_assignable; template<class T> struct is_nothrow_copy_assignable; template<class T> struct is_nothrow_move_assignable; template<class T, class U> struct is_nothrow_swappable_with; template<class T> struct is_nothrow_swappable; template<class T> struct is_nothrow_destructible; template<class T> struct has_virtual_destructor; template<class T> struct has_unique_object_representations; template<class T, class U> struct reference_constructs_from_temporary; template<class T, class U> struct reference_converts_from_temporary; // type property queries template<class T> struct alignment_of; template<class T> struct rank; template<class T, unsigned I = 0> struct extent; // type relations template<class T, class U> struct is_same; template<class Base, class Derived> struct is_base_of; template<class From, class To> struct is_convertible; template<class From, class To> struct is_nothrow_convertible; template<class T, class U> struct is_layout_compatible; template<class Base, class Derived> struct is_pointer_interconvertible_base_of; template<class Fn, class... ArgTypes> struct is_invocable; template<class R, class Fn, class... ArgTypes> struct is_invocable_r; template<class Fn, class... ArgTypes> struct is_nothrow_invocable; template<class R, class Fn, class... ArgTypes> struct is_nothrow_invocable_r; // const-volatile modifications template<class T> struct remove_const; template<class T> struct remove_volatile; template<class T> struct remove_cv; template<class T> struct add_const; template<class T> struct add_volatile; template<class T> struct add_cv; template<class T> using remove_const_t = typename remove_const<T>::type; template<class T> using remove_volatile_t = typename remove_volatile<T>::type; template<class T> using remove_cv_t = typename remove_cv<T>::type; template<class T> using add_const_t = typename add_const<T>::type; template<class T> using add_volatile_t = typename add_volatile<T>::type; template<class T> using add_cv_t = typename add_cv<T>::type; // reference modifications template<class T> struct remove_reference; template<class T> struct add_lvalue_reference; template<class T> struct add_rvalue_reference; template<class T> using remove_reference_t = typename remove_reference<T>::type; template<class T> using add_lvalue_reference_t = typename add_lvalue_reference<T>::type; template<class T> using add_rvalue_reference_t = typename add_rvalue_reference<T>::type; // sign modifications template<class T> struct make_signed; template<class T> struct make_unsigned; template<class T> using make_signed_t = typename make_signed<T>::type; template<class T> using make_unsigned_t = typename make_unsigned<T>::type; // array modifications template<class T> struct remove_extent; template<class T> struct remove_all_extents; template<class T> using remove_extent_t = typename remove_extent<T>::type; template<class T> using remove_all_extents_t = typename remove_all_extents<T>::type; // pointer modifications template<class T> struct remove_pointer; template<class T> struct add_pointer; template<class T> using remove_pointer_t = typename remove_pointer<T>::type; template<class T> using add_pointer_t = typename add_pointer<T>::type; // other transformations template<class T> struct type_identity; template<class T> struct remove_cvref; template<class T> struct decay; template<bool, class T = void> struct enable_if; template<bool, class T, class F> struct conditional; template<class... T> struct common_type; template<class T, class U, template<class> class TQual, template<class> class UQual> struct basic_common_reference { }; template<class... T> struct common_reference; template<class T> struct underlying_type; template<class Fn, class... ArgTypes> struct invoke_result; template<class T> struct unwrap_reference; template<class T> struct unwrap_ref_decay; template<class T> using type_identity_t = typename type_identity<T>::type; template<class T> using remove_cvref_t = typename remove_cvref<T>::type; template<class T> using decay_t = typename decay<T>::type; template<bool b, class T = void> using enable_if_t = typename enable_if<b, T>::type; template<bool b, class T, class F> using conditional_t = typename conditional<b, T, F>::type; template<class... T> using common_type_t = typename common_type<T...>::type; template<class... T> using common_reference_t = typename common_reference<T...>::type; template<class T> using underlying_type_t = typename underlying_type<T>::type; template<class Fn, class... ArgTypes> using invoke_result_t = typename invoke_result<Fn, ArgTypes...>::type; template<class T> using unwrap_reference_t = typename unwrap_reference<T>::type; template<class T> using unwrap_ref_decay_t = typename unwrap_ref_decay<T>::type; template<class...> using void_t = void; // logical operator traits template<class... B> struct conjunction; template<class... B> struct disjunction; template<class B> struct negation; // primary type categories template<class T> inline constexpr bool is_void_v = is_void<T>::value; template<class T> inline constexpr bool is_null_pointer_v = is_null_pointer<T>::value; template<class T> inline constexpr bool is_integral_v = is_integral<T>::value; template<class T> inline constexpr bool is_floating_point_v = is_floating_point<T>::value; template<class T> inline constexpr bool is_array_v = is_array<T>::value; template<class T> inline constexpr bool is_pointer_v = is_pointer<T>::value; template<class T> inline constexpr bool is_lvalue_reference_v = is_lvalue_reference<T>::value; template<class T> inline constexpr bool is_rvalue_reference_v = is_rvalue_reference<T>::value; template<class T> inline constexpr bool is_member_object_pointer_v = is_member_object_pointer<T>::value; template<class T> inline constexpr bool is_member_function_pointer_v = is_member_function_pointer<T>::value; template<class T> inline constexpr bool is_enum_v = is_enum<T>::value; template<class T> inline constexpr bool is_union_v = is_union<T>::value; template<class T> inline constexpr bool is_class_v = is_class<T>::value; template<class T> inline constexpr bool is_function_v = is_function<T>::value; // composite type categories template<class T> inline constexpr bool is_reference_v = is_reference<T>::value; template<class T> inline constexpr bool is_arithmetic_v = is_arithmetic<T>::value; template<class T> inline constexpr bool is_fundamental_v = is_fundamental<T>::value; template<class T> inline constexpr bool is_object_v = is_object<T>::value; template<class T> inline constexpr bool is_scalar_v = is_scalar<T>::value; template<class T> inline constexpr bool is_compound_v = is_compound<T>::value; template<class T> inline constexpr bool is_member_pointer_v = is_member_pointer<T>::value; // type properties template<class T> inline constexpr bool is_const_v = is_const<T>::value; template<class T> inline constexpr bool is_volatile_v = is_volatile<T>::value; template<class T> inline constexpr bool is_trivial_v = is_trivial<T>::value; template<class T> inline constexpr bool is_trivially_copyable_v = is_trivially_copyable<T>::value; template<class T> inline constexpr bool is_standard_layout_v = is_standard_layout<T>::value; template<class T> inline constexpr bool is_empty_v = is_empty<T>::value; template<class T> inline constexpr bool is_polymorphic_v = is_polymorphic<T>::value; template<class T> inline constexpr bool is_abstract_v = is_abstract<T>::value; template<class T> inline constexpr bool is_final_v = is_final<T>::value; template<class T> inline constexpr bool is_aggregate_v = is_aggregate<T>::value; template<class T> inline constexpr bool is_signed_v = is_signed<T>::value; template<class T> inline constexpr bool is_unsigned_v = is_unsigned<T>::value; template<class T> inline constexpr bool is_bounded_array_v = is_bounded_array<T>::value; template<class T> inline constexpr bool is_unbounded_array_v = is_unbounded_array<T>::value; template<class T> inline constexpr bool is_scoped_enum_v = is_scoped_enum<T>::value; template<class T, class... Args> inline constexpr bool is_constructible_v = is_constructible<T, Args...>::value; template<class T> inline constexpr bool is_default_constructible_v = is_default_constructible<T>::value; template<class T> inline constexpr bool is_copy_constructible_v = is_copy_constructible<T>::value; template<class T> inline constexpr bool is_move_constructible_v = is_move_constructible<T>::value; template<class T, class U> inline constexpr bool is_assignable_v = is_assignable<T, U>::value; template<class T> inline constexpr bool is_copy_assignable_v = is_copy_assignable<T>::value; template<class T> inline constexpr bool is_move_assignable_v = is_move_assignable<T>::value; template<class T, class U> inline constexpr bool is_swappable_with_v = is_swappable_with<T, U>::value; template<class T> inline constexpr bool is_swappable_v = is_swappable<T>::value; template<class T> inline constexpr bool is_destructible_v = is_destructible<T>::value; template<class T, class... Args> inline constexpr bool is_trivially_constructible_v = is_trivially_constructible<T, Args...>::value; template<class T> inline constexpr bool is_trivially_default_constructible_v = is_trivially_default_constructible<T>::value; template<class T> inline constexpr bool is_trivially_copy_constructible_v = is_trivially_copy_constructible<T>::value; template<class T> inline constexpr bool is_trivially_move_constructible_v = is_trivially_move_constructible<T>::value; template<class T, class U> inline constexpr bool is_trivially_assignable_v = is_trivially_assignable<T, U>::value; template<class T> inline constexpr bool is_trivially_copy_assignable_v = is_trivially_copy_assignable<T>::value; template<class T> inline constexpr bool is_trivially_move_assignable_v = is_trivially_move_assignable<T>::value; template<class T> inline constexpr bool is_trivially_destructible_v = is_trivially_destructible<T>::value; template<class T, class... Args> inline constexpr bool is_nothrow_constructible_v = is_nothrow_constructible<T, Args...>::value; template<class T> inline constexpr bool is_nothrow_default_constructible_v = is_nothrow_default_constructible<T>::value; template<class T> inline constexpr bool is_nothrow_copy_constructible_v = is_nothrow_copy_constructible<T>::value; template<class T> inline constexpr bool is_nothrow_move_constructible_v = is_nothrow_move_constructible<T>::value; template<class T, class U> inline constexpr bool is_nothrow_assignable_v = is_nothrow_assignable<T, U>::value; template<class T> inline constexpr bool is_nothrow_copy_assignable_v = is_nothrow_copy_assignable<T>::value; template<class T> inline constexpr bool is_nothrow_move_assignable_v = is_nothrow_move_assignable<T>::value; template<class T, class U> inline constexpr bool is_nothrow_swappable_with_v = is_nothrow_swappable_with<T, U>::value; template<class T> inline constexpr bool is_nothrow_swappable_v = is_nothrow_swappable<T>::value; template<class T> inline constexpr bool is_nothrow_destructible_v = is_nothrow_destructible<T>::value; template<class T> inline constexpr bool has_virtual_destructor_v = has_virtual_destructor<T>::value; template<class T> inline constexpr bool has_unique_object_representations_v = has_unique_object_representations<T>::value; template<class T, class U> inline constexpr bool reference_constructs_from_temporary_v = reference_constructs_from_temporary<T, U>::value; template<class T, class U> inline constexpr bool reference_converts_from_temporary_v = reference_converts_from_temporary<T, U>::value; // type property queries template<class T> inline constexpr size_t alignment_of_v = alignment_of<T>::value; template<class T> inline constexpr size_t rank_v = rank<T>::value; template<class T, unsigned I = 0> inline constexpr size_t extent_v = extent<T, I>::value; // type relations template<class T, class U> inline constexpr bool is_same_v = is_same<T, U>::value; template<class Base, class Derived> inline constexpr bool is_base_of_v = is_base_of<Base, Derived>::value; template<class From, class To> inline constexpr bool is_convertible_v = is_convertible<From, To>::value; template<class From, class To> inline constexpr bool is_nothrow_convertible_v = is_nothrow_convertible<From, To>::value; template<class T, class U> inline constexpr bool is_layout_compatible_v = is_layout_compatible<T, U>::value; template<class Base, class Derived> inline constexpr bool is_pointer_interconvertible_base_of_v = is_pointer_interconvertible_base_of<Base, Derived>::value; template<class Fn, class... ArgTypes> inline constexpr bool is_invocable_v = is_invocable<Fn, ArgTypes...>::value; template<class R, class Fn, class... ArgTypes> inline constexpr bool is_invocable_r_v = is_invocable_r<R, Fn, ArgTypes...>::value; template<class Fn, class... ArgTypes> inline constexpr bool is_nothrow_invocable_v = is_nothrow_invocable<Fn, ArgTypes...>::value; template<class R, class Fn, class... ArgTypes> inline constexpr bool is_nothrow_invocable_r_v = is_nothrow_invocable_r<R, Fn, ArgTypes...>::value; // logical operator traits template<class... B> inline constexpr bool conjunction_v = conjunction<B...>::value; template<class... B> inline constexpr bool disjunction_v = disjunction<B...>::value; template<class B> inline constexpr bool negation_v = negation<B>::value; // member relationships template<class S, class M> constexpr bool is_pointer_interconvertible_with_class(M S::*m) noexcept; template<class S1, class S2, class M1, class M2> constexpr bool is_corresponding_member(M1 S1::*m1, M2 S2::*m2) noexcept; // constant evaluation context constexpr bool is_constant_evaluated() noexcept; } ``` #### Class template `[std::integral\_constant](../types/integral_constant "cpp/types/integral constant")` ``` namespace std { template <class T, T v> struct integral_constant { static constexpr T value = v; using value_type = T; using type = integral_constant<T, v>; constexpr operator value_type() const noexcept { return value; } constexpr value_type operator()() const noexcept { return value; } }; } ```
programming_docs
cpp Standard library header <numbers> (C++20) Standard library header <numbers> (C++20) ========================================= This header is part of the [numeric](../numeric "cpp/numeric") library. ### [Mathematical constants](../numeric/constants "cpp/numeric/constants") (since C++20) The header **`<numbers>`** provides several mathematical constants, such as `[std::numbers::pi](../numeric/constants "cpp/numeric/constants")` or `[std::numbers::sqrt2](../numeric/constants "cpp/numeric/constants")`. ### Synopsis ``` namespace std::numbers { template<class T> inline constexpr T e_v = /* unspecified */; template<class T> inline constexpr T log2e_v = /* unspecified */; template<class T> inline constexpr T log10e_v = /* unspecified */; template<class T> inline constexpr T pi_v = /* unspecified */; template<class T> inline constexpr T inv_pi_v = /* unspecified */; template<class T> inline constexpr T inv_sqrtpi_v = /* unspecified */; template<class T> inline constexpr T ln2_v = /* unspecified */; template<class T> inline constexpr T ln10_v = /* unspecified */; template<class T> inline constexpr T sqrt2_v = /* unspecified */; template<class T> inline constexpr T sqrt3_v = /* unspecified */; template<class T> inline constexpr T inv_sqrt3_v = /* unspecified */; template<class T> inline constexpr T egamma_v = /* unspecified */; template<class T> inline constexpr T phi_v = /* unspecified */; template<floating_point T> inline constexpr T e_v<T> = /* see description */; template<floating_point T> inline constexpr T log2e_v<T> = /* see description */; template<floating_point T> inline constexpr T log10e_v<T> = /* see description */; template<floating_point T> inline constexpr T pi_v<T> = /* see description */; template<floating_point T> inline constexpr T inv_pi_v<T> = /* see description */; template<floating_point T> inline constexpr T inv_sqrtpi_v<T> = /* see description */; template<floating_point T> inline constexpr T ln2_v<T> = /* see description */; template<floating_point T> inline constexpr T ln10_v<T> = /* see description */; template<floating_point T> inline constexpr T sqrt2_v<T> = /* see description */; template<floating_point T> inline constexpr T sqrt3_v<T> = /* see description */; template<floating_point T> inline constexpr T inv_sqrt3_v<T> = /* see description */; template<floating_point T> inline constexpr T egamma_v<T> = /* see description */; template<floating_point T> inline constexpr T phi_v<T> = /* see description */; inline constexpr double e = e_v<double>; inline constexpr double log2e = log2e_v<double>; inline constexpr double log10e = log10e_v<double>; inline constexpr double pi = pi_v<double>; inline constexpr double inv_pi = inv_pi_v<double>; inline constexpr double inv_sqrtpi = inv_sqrtpi_v<double>; inline constexpr double ln2 = ln2_v<double>; inline constexpr double ln10 = ln10_v<double>; inline constexpr double sqrt2 = sqrt2_v<double>; inline constexpr double sqrt3 = sqrt3_v<double>; inline constexpr double inv_sqrt3 = inv_sqrt3_v<double>; inline constexpr double egamma = egamma_v<double>; inline constexpr double phi = phi_v<double>; } ``` cpp Standard library header <climits> Standard library header <climits> ================================= This header was originally in the C standard library as `<limits.h>`. This header is part of the [type support](../types "cpp/types") library, in particular it's part of the [C numeric limits interface](../types/climits "cpp/types/climits"). ### Macros | | | | --- | --- | | CHAR\_BIT | number of bits in a byte (macro constant) | | MB\_LEN\_MAX | maximum number of bytes in a multibyte character (macro constant) | | CHAR\_MIN | minimum value of `char` (macro constant) | | CHAR\_MAX | maximum value of `char` (macro constant) | | SCHAR\_MINSHRT\_MININT\_MINLONG\_MINLLONG\_MIN (C++11) | minimum value of `signed char`, `short`, `int`, `long` and `long long` respectively (macro constant) | | SCHAR\_MAXSHRT\_MAXINT\_MAXLONG\_MAXLLONG\_MAX (C++11) | maximum value of `signed char`, `short`, `int`, `long` and `long long` respectively (macro constant) | | UCHAR\_MAXUSHRT\_MAXUINT\_MAXULONG\_MAXULLONG\_MAX (C++11) | maximum value of `unsigned char`, `unsigned short`, `unsigned int`,`unsigned long` and `unsigned long long` respectively (macro constant) | ### Synopsis ``` #define CHAR_BIT /* see definition */ #define SCHAR_MIN /* see definition */ #define SCHAR_MAX /* see definition */ #define UCHAR_MAX /* see definition */ #define CHAR_MIN /* see definition */ #define CHAR_MAX /* see definition */ #define MB_LEN_MAX /* see definition */ #define SHRT_MIN /* see definition */ #define SHRT_MAX /* see definition */ #define USHRT_MAX /* see definition */ #define INT_MIN /* see definition */ #define INT_MAX /* see definition */ #define UINT_MAX /* see definition */ #define LONG_MIN /* see definition */ #define LONG_MAX /* see definition */ #define ULONG_MAX /* see definition */ #define LLONG_MIN /* see definition */ #define LLONG_MAX /* see definition */ #define ULLONG_MAX /* see definition */ ``` cpp Standard library header <cinttypes> (C++11) Standard library header <cinttypes> (C++11) =========================================== This header was originally in the C standard library as `<inttypes.h>`. | | | --- | | Includes | | [<cstdint>](cstdint "cpp/header/cstdint") (C++11) | [Fixed-width integer types](../types/integer "cpp/types/integer") and [limits of other types](../types/climits "cpp/types/climits") | | Types | | [imaxdiv\_t](../numeric/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) | | Functions | | [abs(std::intmax\_t)imaxabs](../numeric/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](../numeric/math/div "cpp/numeric/math/div") (C++11)(C++11) | computes quotient and remainder of integer division (function) | | [strtoimaxstrtoumax](../string/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) | | [wcstoimaxwcstoumax](../string/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) | | Macros | | Format constants for the `[std::fprintf](../io/c/fprintf "cpp/io/c/fprintf")` family of functions | | PRId8PRId16PRId32PRId64PRIdLEAST8PRIdLEAST16PRIdLEAST32PRIdLEAST64PRIdFAST8PRIdFAST16PRIdFAST32PRIdFAST64PRIdMAXPRIdPTR (C++11) | format conversion specifier to output a signed decimal integer value of type `[std::int8\_t](../types/integer "cpp/types/integer")`, `[std::int16\_t](../types/integer "cpp/types/integer")`, `[std::int32\_t](../types/integer "cpp/types/integer")`, `[std::int64\_t](../types/integer "cpp/types/integer")`, `[std::int\_least8\_t](../types/integer "cpp/types/integer")`, `[std::int\_least16\_t](../types/integer "cpp/types/integer")`, `[std::int\_least32\_t](../types/integer "cpp/types/integer")`, `[std::int\_least64\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::intmax\_t](../types/integer "cpp/types/integer")`, `[std::intptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `d` for `int` (macro constant) | | PRIi8PRIi16PRIi32PRIi64PRIiLEAST8PRIiLEAST16PRIiLEAST32PRIiLEAST64PRIiFAST8PRIiFAST16PRIiFAST32PRIiFAST64PRIiMAXPRIiPTR (C++11) | format conversion specifier to output a signed decimal integer value of type `[std::int8\_t](../types/integer "cpp/types/integer")`, `[std::int16\_t](../types/integer "cpp/types/integer")`, `[std::int32\_t](../types/integer "cpp/types/integer")`, `[std::int64\_t](../types/integer "cpp/types/integer")`, `[std::int\_least8\_t](../types/integer "cpp/types/integer")`, `[std::int\_least16\_t](../types/integer "cpp/types/integer")`, `[std::int\_least32\_t](../types/integer "cpp/types/integer")`, `[std::int\_least64\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::intmax\_t](../types/integer "cpp/types/integer")`, `[std::intptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `i` for `int` (macro constant) | | PRIu8PRIu16PRIu32PRIu64PRIuLEAST8PRIuLEAST16PRIuLEAST32PRIuLEAST64PRIuFAST8PRIuFAST16PRIuFAST32PRIuFAST64PRIuMAXPRIuPTR (C++11) | format conversion specifier to output an unsigned decimal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `u` for `unsigned int` (macro constant) | | PRIo8PRIo16PRIo32PRIo64PRIoLEAST8PRIoLEAST16PRIoLEAST32PRIoLEAST64PRIoFAST8PRIoFAST16PRIoFAST32PRIoFAST64PRIoMAXPRIoPTR (C++11) | format conversion specifier to output an unsigned octal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `o` for `unsigned int` (macro constant) | | PRIx8PRIx16PRIx32PRIx64PRIxLEAST8PRIxLEAST16PRIxLEAST32PRIxLEAST64PRIxFAST8PRIxFAST16PRIxFAST32PRIxFAST64PRIxMAXPRIxPTR (C++11) | format conversion specifier to output an unsigned lowercase hexadecimal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `x` for `unsigned int` (macro constant) | | PRIX8PRIX16PRIX32PRIX64PRIXLEAST8PRIXLEAST16PRIXLEAST32PRIXLEAST64PRIXFAST8PRIXFAST16PRIXFAST32PRIXFAST64PRIXMAXPRIXPTR (C++11) | format conversion specifier to output an unsigned uppercase hexadecimal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `X` for `unsigned int` (macro constant) | | Format constants for the `[std::fscanf](../io/c/fscanf "cpp/io/c/fscanf")` family of functions | | SCNd8SCNd16SCNd32SCNd64SCNdLEAST8SCNdLEAST16SCNdLEAST32SCNdLEAST64SCNdFAST8SCNdFAST16SCNdFAST32SCNdFAST64SCNdMAXSCNdPTR (C++11) | format conversion specifier to input a signed decimal integer value of type `[std::int8\_t](../types/integer "cpp/types/integer")`, `[std::int16\_t](../types/integer "cpp/types/integer")`, `[std::int32\_t](../types/integer "cpp/types/integer")`, `[std::int64\_t](../types/integer "cpp/types/integer")`, `[std::int\_least8\_t](../types/integer "cpp/types/integer")`, `[std::int\_least16\_t](../types/integer "cpp/types/integer")`, `[std::int\_least32\_t](../types/integer "cpp/types/integer")`, `[std::int\_least64\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::intmax\_t](../types/integer "cpp/types/integer")`, `[std::intptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `d` for `int` (macro constant) | | SCNi8SCNi16SCNi32SCNi64SCNiLEAST8SCNiLEAST16SCNiLEAST32SCNiLEAST64SCNiFAST8SCNiFAST16SCNiFAST32SCNiFAST64SCNiMAXSCNiPTR (C++11) | format conversion specifier to input a signed decimal/octal/hexadecimal integer value of type `[std::int8\_t](../types/integer "cpp/types/integer")`, `[std::int16\_t](../types/integer "cpp/types/integer")`, `[std::int32\_t](../types/integer "cpp/types/integer")`, `[std::int64\_t](../types/integer "cpp/types/integer")`, `[std::int\_least8\_t](../types/integer "cpp/types/integer")`, `[std::int\_least16\_t](../types/integer "cpp/types/integer")`, `[std::int\_least32\_t](../types/integer "cpp/types/integer")`, `[std::int\_least64\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::int\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::intmax\_t](../types/integer "cpp/types/integer")`, `[std::intptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `i` for `int` (macro constant) | | SCNu8SCNu16SCNu32SCNu64SCNuLEAST8SCNuLEAST16SCNuLEAST32SCNuLEAST64SCNuFAST8SCNuFAST16SCNuFAST32SCNuFAST64SCNuMAXSCNuPTR (C++11) | format conversion specifier to input an unsigned decimal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `u` for `unsigned int` (macro constant) | | SCNo8SCNo16SCNo32SCNo64SCNoLEAST8SCNoLEAST16SCNoLEAST32SCNoLEAST64SCNoFAST8SCNoFAST16SCNoFAST32SCNoFAST64SCNoMAXSCNoPTR (C++11) | format conversion specifier to input an unsigned octal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `o` for `unsigned int` (macro constant) | | SCNx8SCNx16SCNx32SCNx64SCNxLEAST8SCNxLEAST16SCNxLEAST32SCNxLEAST64SCNxFAST8SCNxFAST16SCNxFAST32SCNxFAST64SCNxMAXSCNxPTR (C++11) | format conversion specifier to input an unsigned hexadecimal integer value of type `[std::uint8\_t](../types/integer "cpp/types/integer")`, `[std::uint16\_t](../types/integer "cpp/types/integer")`, `[std::uint32\_t](../types/integer "cpp/types/integer")`, `[std::uint64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_least64\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast8\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast16\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast32\_t](../types/integer "cpp/types/integer")`, `[std::uint\_fast64\_t](../types/integer "cpp/types/integer")`, `[std::uintmax\_t](../types/integer "cpp/types/integer")`, `[std::uintptr\_t](../types/integer "cpp/types/integer")` respectively, equivalent to `x` for `unsigned int` (macro constant) | ### Synopsis ``` #include <cstdint> namespace std { using imaxdiv_t = /* see description */; intmax_t imaxabs(intmax_t j); imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom); intmax_t strtoimax(const char* nptr, char** endptr, int base); uintmax_t strtoumax(const char* nptr, char** endptr, int base); intmax_t wcstoimax(const wchar_t* nptr, wchar_t** endptr, int base); uintmax_t wcstoumax(const wchar_t* nptr, wchar_t** endptr, int base); intmax_t abs(intmax_t); // optional, see description imaxdiv_t div(intmax_t, intmax_t); // optional, see description } #define PRIdN /* see description */ #define PRIiN /* see description */ #define PRIoN /* see description */ #define PRIuN /* see description */ #define PRIxN /* see description */ #define PRIXN /* see description */ #define SCNdN /* see description */ #define SCNiN /* see description */ #define SCNoN /* see description */ #define SCNuN /* see description */ #define SCNxN /* see description */ #define PRIdLEASTN /* see description */ #define PRIiLEASTN /* see description */ #define PRIoLEASTN /* see description */ #define PRIuLEASTN /* see description */ #define PRIxLEASTN /* see description */ #define PRIXLEASTN /* see description */ #define SCNdLEASTN /* see description */ #define SCNiLEASTN /* see description */ #define SCNoLEASTN /* see description */ #define SCNuLEASTN /* see description */ #define SCNxLEASTN /* see description */ #define PRIdFASTN /* see description */ #define PRIiFASTN /* see description */ #define PRIoFASTN /* see description */ #define PRIuFASTN /* see description */ #define PRIxFASTN /* see description */ #define PRIXFASTN /* see description */ #define SCNdFASTN /* see description */ #define SCNiFASTN /* see description */ #define SCNoFASTN /* see description */ #define SCNuFASTN /* see description */ #define SCNxFASTN /* see description */ #define PRIdMAX /* see description */ #define PRIiMAX /* see description */ #define PRIoMAX /* see description */ #define PRIuMAX /* see description */ #define PRIxMAX /* see description */ #define PRIXMAX /* see description */ #define SCNdMAX /* see description */ #define SCNiMAX /* see description */ #define SCNoMAX /* see description */ #define SCNuMAX /* see description */ #define SCNxMAX /* see description */ #define PRIdPTR /* see description */ #define PRIiPTR /* see description */ #define PRIoPTR /* see description */ #define PRIuPTR /* see description */ #define PRIxPTR /* see description */ #define PRIXPTR /* see description */ #define SCNdPTR /* see description */ #define SCNiPTR /* see description */ #define SCNoPTR /* see description */ #define SCNuPTR /* see description */ #define SCNxPTR /* see description */ ```
programming_docs
cpp Standard library header <condition_variable> (C++11) Standard library header <condition\_variable> (C++11) ===================================================== This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [condition\_variable](../thread/condition_variable "cpp/thread/condition variable") (C++11) | provides a condition variable associated with a `[std::unique\_lock](../thread/unique_lock "cpp/thread/unique lock")` (class) | | [condition\_variable\_any](../thread/condition_variable_any "cpp/thread/condition variable any") (C++11) | provides a condition variable associated with any lock type (class) | | [cv\_status](../thread/cv_status "cpp/thread/cv status") (C++11) | lists the possible results of timed waits on condition variables (enum) | | Functions | | [notify\_all\_at\_thread\_exit](../thread/notify_all_at_thread_exit "cpp/thread/notify all at thread exit") (C++11) | schedules a call to `notify_all` to be invoked when this thread is completely finished (function) | ### Synopsis ``` namespace std { class condition_variable; class condition_variable_any; void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk); enum class cv_status { no_timeout, timeout }; } ``` #### Class `[std::condition\_variable](../thread/condition_variable "cpp/thread/condition variable")` ``` namespace std { class condition_variable { public: condition_variable(); ~condition_variable(); condition_variable(const condition_variable&) = delete; condition_variable& operator=(const condition_variable&) = delete; void notify_one() noexcept; void notify_all() noexcept; void wait(unique_lock<mutex>& lock); template<class Pred> void wait(unique_lock<mutex>& lock, Pred pred); template<class Clock, class Duration> cv_status wait_until(unique_lock<mutex>& lock, const chrono::time_point<Clock, Duration>& abs_time); template<class Clock, class Duration, class Pred> bool wait_until(unique_lock<mutex>& lock, const chrono::time_point<Clock, Duration>& abs_time, Pred pred); template<class Rep, class Period> cv_status wait_for(unique_lock<mutex>& lock, const chrono::duration<Rep, Period>& rel_time); template<class Rep, class Period, class Pred> bool wait_for(unique_lock<mutex>& lock, const chrono::duration<Rep, Period>& rel_time, Pred pred); using native_handle_type = /* implementation-defined */; native_handle_type native_handle(); }; } ``` #### Class `[std::condition\_variable\_any](../thread/condition_variable_any "cpp/thread/condition variable any")` ``` namespace std { class condition_variable_any { public: condition_variable_any(); ~condition_variable_any(); condition_variable_any(const condition_variable_any&) = delete; condition_variable_any& operator=(const condition_variable_any&) = delete; void notify_one() noexcept; void notify_all() noexcept; // noninterruptible waits template<class Lock> void wait(Lock& lock); template<class Lock, class Pred> void wait(Lock& lock, Pred pred); template<class Lock, class Clock, class Duration> cv_status wait_until(Lock& lock, const chrono::time_point<Clock, Duration>& abs_time); template<class Lock, class Clock, class Duration, class Pred> bool wait_until(Lock& lock, const chrono::time_point<Clock, Duration>& abs_time, Pred pred); template<class Lock, class Rep, class Period> cv_status wait_for(Lock& lock, const chrono::duration<Rep, Period>& rel_time); template<class Lock, class Rep, class Period, class Pred> bool wait_for(Lock& lock, const chrono::duration<Rep, Period>& rel_time, Pred pred); // interruptible waits template<class Lock, class Pred> bool wait(Lock& lock, stop_token stoken, Pred pred); template<class Lock, class Clock, class Duration, class Pred> bool wait_until(Lock& lock, stop_token stoken, const chrono::time_point<Clock, Duration>& abs_time, Pred pred); template<class Lock, class Rep, class Period, class Pred> bool wait_for(Lock& lock, stop_token stoken, const chrono::duration<Rep, Period>& rel_time, Pred pred); }; } ``` cpp Standard library header <ranges> (C++20) Standard library header <ranges> (C++20) ======================================== This header is part of the [ranges](../ranges "cpp/ranges") library. ### Namespace aliases | | | | | --- | --- | --- | | ``` namespace std { namespace views = ranges::views; } ``` | | | The namespace alias `std::views` is provided as a shorthand for `std::ranges::views`. | | | --- | | Concepts | | Range concepts | | Defined in namespace `std::ranges` | | [ranges::range](../ranges/range "cpp/ranges/range") (C++20) | specifies that a type is a range, that is, it provides a `begin` iterator and an `end` sentinel (concept) | | [ranges::borrowed\_range](../ranges/borrowed_range "cpp/ranges/borrowed range") (C++20) | specifies that a type is a [`range`](../ranges/range "cpp/ranges/range") and iterators obtained from an expression of it can be safely returned without danger of dangling (concept) | | [ranges::sized\_range](../ranges/sized_range "cpp/ranges/sized range") (C++20) | specifies that a range knows its size in constant time (concept) | | [ranges::view](../ranges/view "cpp/ranges/view") (C++20) | specifies that a range is a view, that is, it has constant time copy/move/assignment (concept) | | [ranges::input\_range](../ranges/input_range "cpp/ranges/input range") (C++20) | specifies a range whose iterator type satisfies [`input_iterator`](../iterator/input_iterator "cpp/iterator/input iterator") (concept) | | [ranges::output\_range](../ranges/output_range "cpp/ranges/output range") (C++20) | specifies a range whose iterator type satisfies [`output_iterator`](../iterator/output_iterator "cpp/iterator/output iterator") (concept) | | [ranges::forward\_range](../ranges/forward_range "cpp/ranges/forward range") (C++20) | specifies a range whose iterator type satisfies [`forward_iterator`](../iterator/forward_iterator "cpp/iterator/forward iterator") (concept) | | [ranges::bidirectional\_range](../ranges/bidirectional_range "cpp/ranges/bidirectional range") (C++20) | specifies a range whose iterator type satisfies [`bidirectional_iterator`](../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") (concept) | | [ranges::random\_access\_range](../ranges/random_access_range "cpp/ranges/random access range") (C++20) | specifies a range whose iterator type satisfies [`random_access_iterator`](../iterator/random_access_iterator "cpp/iterator/random access iterator") (concept) | | [ranges::contiguous\_range](../ranges/contiguous_range "cpp/ranges/contiguous range") (C++20) | specifies a range whose iterator type satisfies [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") (concept) | | [ranges::common\_range](../ranges/common_range "cpp/ranges/common range") (C++20) | specifies that a range has identical iterator and sentinel types (concept) | | [ranges::viewable\_range](../ranges/viewable_range "cpp/ranges/viewable range") (C++20) | specifies the requirements for a [`range`](../ranges/range "cpp/ranges/range") to be safely convertible to a [`view`](../ranges/view "cpp/ranges/view") (concept) | | [ranges::constant\_range](../ranges/constant_range "cpp/ranges/constant range") (C++23) | specifies that a range has read-only elements (concept) | | Functions | | Range conversions | | Defined in namespace `std::ranges` | | [ranges::to](../ranges/to "cpp/ranges/to") (C++23) | constructs a non-view range from another range (function template) | | Classes | | Range primitives | | Defined in namespace `std::ranges` | | [ranges::iterator\_tranges::const\_iterator\_tranges::sentinel\_tranges::range\_difference\_tranges::range\_size\_t ranges::range\_value\_tranges::range\_reference\_tranges::range\_const\_reference\_tranges::range\_rvalue\_reference\_t](../ranges/iterator_t "cpp/ranges/iterator t") (C++20)(C++23)(C++20)(C++20)(C++20)(C++20)(C++20)(C++23)(C++20) | obtains associated types of a range (alias template) | | Views | | Defined in namespace `std::ranges` | | [ranges::view\_interface](../ranges/view_interface "cpp/ranges/view interface") (C++20) | helper class template for defining a [`view`](../ranges/view "cpp/ranges/view"), using the [curiously recurring template pattern](../language/crtp "cpp/language/crtp") (class template) | | [ranges::subrange](../ranges/subrange "cpp/ranges/subrange") (C++20) | combines an iterator-sentinel pair into a [`view`](../ranges/view "cpp/ranges/view") (class template) | | Dangling iterator handling | | Defined in namespace `std::ranges` | | [ranges::dangling](../ranges/dangling "cpp/ranges/dangling") (C++20) | a placeholder type indicating that an iterator or a `subrange` should not be returned since it would be dangling (class) | | [ranges::borrowed\_iterator\_tranges::borrowed\_subrange\_t](../ranges/borrowed_iterator_t "cpp/ranges/borrowed iterator t") (C++20) | obtains iterator type or `subrange` type of a [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") (alias template) | | Range adaptor objects utility | | Defined in namespace `std::ranges` | | [ranges::range\_adaptor\_closure](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/range_adaptor_closure&action=edit&redlink=1 "cpp/ranges/range adaptor closure (page does not exist)") (C++23) | helper base class template for defining a range adaptor closure object (class template) | | Factories | | Defined in namespace `std::ranges` | | [ranges::empty\_viewviews::empty](../ranges/empty_view "cpp/ranges/empty view") (C++20) | an empty [`view`](../ranges/view "cpp/ranges/view") with no elements (class template) (variable template) | | [ranges::single\_viewviews::single](../ranges/single_view "cpp/ranges/single view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") that contains a single element of a specified value (class template) (customization point object) | | [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) | | [ranges::basic\_istream\_viewviews::istream](../ranges/basic_istream_view "cpp/ranges/basic istream view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of the elements obtained by successive application of `operator>>` on the associated input stream (class template) (customization point object) | | [ranges::repeat\_viewviews::repeat](../ranges/repeat_view "cpp/ranges/repeat view") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of a generated sequence by repeatedly producing the same value (class template) (customization point object) | | [ranges::cartesian\_product\_viewviews::cartesian\_product](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/cartesian_product_view&action=edit&redlink=1 "cpp/ranges/cartesian product view (page does not exist)") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of tuples of results calculated by the n-ary cartesian product of the adapted views (class template) (customization point object) | | Adaptors | | Defined in namespace `std::ranges` | | [views::all\_tviews::all](../ranges/all_view "cpp/ranges/all view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") that includes all elements of a [`range`](../ranges/range "cpp/ranges/range") (alias template) (range adaptor object) | | [ranges::ref\_view](../ranges/ref_view "cpp/ranges/ref view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") of the elements of some other [`range`](../ranges/range "cpp/ranges/range") (class template) | | [ranges::owning\_view](../ranges/owning_view "cpp/ranges/owning view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") with unique ownership of some [`range`](../ranges/range "cpp/ranges/range") (class template) | | [ranges::filter\_viewviews::filter](../ranges/filter_view "cpp/ranges/filter view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") that consists of the elements of a [`range`](../ranges/range "cpp/ranges/range") that satisfies a predicate (class template) (range adaptor object) | | [ranges::transform\_viewviews::transform](../ranges/transform_view "cpp/ranges/transform view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") of a sequence that applies a transformation function to each element (class template) (range adaptor object) | | [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) | | [ranges::take\_while\_viewviews::take\_while](../ranges/take_while_view "cpp/ranges/take while view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of the initial elements of another [`view`](../ranges/view "cpp/ranges/view"), until the first element on which a predicate returns false (class template) (range adaptor object) | | [ranges::drop\_viewviews::drop](../ranges/drop_view "cpp/ranges/drop view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of elements of another [`view`](../ranges/view "cpp/ranges/view"), skipping the first N elements (class template) (range adaptor object) | | [ranges::drop\_while\_viewviews::drop\_while](../ranges/drop_while_view "cpp/ranges/drop while view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of the elements of another [`view`](../ranges/view "cpp/ranges/view"), skipping the initial subsequence of elements until the first element where the predicate returns false (class template) (range adaptor object) | | [ranges::join\_viewviews::join](../ranges/join_view "cpp/ranges/join view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of the sequence obtained from flattening a [`view`](../ranges/view "cpp/ranges/view") of [`range`s](../ranges/range "cpp/ranges/range") (class template) (range adaptor object) | | [ranges::lazy\_split\_viewviews::lazy\_split](../ranges/lazy_split_view "cpp/ranges/lazy split view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") over the subranges obtained from splitting another [`view`](../ranges/view "cpp/ranges/view") using a delimiter (class template) (range adaptor object) | | [ranges::split\_viewviews::split](../ranges/split_view "cpp/ranges/split view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") over the subranges obtained from splitting another [`view`](../ranges/view "cpp/ranges/view") using a delimiter (class template) (range adaptor object) | | [views::counted](../ranges/view_counted "cpp/ranges/view counted") (C++20) | creates a subrange from an iterator and a count (customization point object) | | [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) | | [ranges::reverse\_viewviews::reverse](../ranges/reverse_view "cpp/ranges/reverse view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") that iterates over the elements of another bidirectional view in reverse order (class template) (range adaptor object) | | [ranges::as\_const\_viewviews::as\_const](../ranges/as_const_view "cpp/ranges/as const view") (C++23) | converts a [`view`](../ranges/view "cpp/ranges/view") into a [`constant_range`](../ranges/constant_range "cpp/ranges/constant range") (class template) (range adaptor object) | | [ranges::as\_rvalue\_viewviews::as\_rvalue](../ranges/as_rvalue_view "cpp/ranges/as rvalue view") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") of a sequence that casts each element to an rvalue (class template) (range adaptor object) | | [ranges::elements\_viewviews::elements](../ranges/elements_view "cpp/ranges/elements view") (C++20) | takes a [`view`](../ranges/view "cpp/ranges/view") consisting of tuple-like values and a number N and produces a [`view`](../ranges/view "cpp/ranges/view") of N'th element of each tuple (class template) (range adaptor object) | | [ranges::keys\_viewviews::keys](../ranges/keys_view "cpp/ranges/keys view") (C++20) | takes a [`view`](../ranges/view "cpp/ranges/view") consisting of pair-like values and produces a [`view`](../ranges/view "cpp/ranges/view") of the first elements of each pair (class template) (range adaptor object) | | [ranges::values\_viewviews::values](../ranges/values_view "cpp/ranges/values view") (C++20) | takes a [`view`](../ranges/view "cpp/ranges/view") consisting of pair-like values and produces a [`view`](../ranges/view "cpp/ranges/view") of the second elements of each pair (class template) (range adaptor object) | | [ranges::zip\_viewviews::zip](../ranges/zip_view "cpp/ranges/zip view") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of tuples of references to corresponding elements of the adapted views (class template) (customization point object) | | [ranges::zip\_transform\_viewviews::zip\_transform](../ranges/zip_transform_view "cpp/ranges/zip transform view") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of tuples of results of application of a transformation function to corresponding elements of the adapted views (class template) (customization point object) | | [ranges::adjacent\_viewviews::adjacent](../ranges/adjacent_view "cpp/ranges/adjacent view") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of tuples of references to adjacent elements of the adapted view (class template) (range adaptor object) | | [ranges::adjacent\_transform\_viewviews::adjacent\_transform](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/adjacent_transform_view&action=edit&redlink=1 "cpp/ranges/adjacent transform view (page does not exist)") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of tuples of results of application of a transformation function to adjacent elements of the adapted view (class template) (range adaptor object) | | [ranges::join\_with\_viewviews::join\_with](../ranges/join_with_view "cpp/ranges/join with view") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of the sequence obtained from flattening a view of ranges, with the delimiter in between elements (class template) (range adaptor object) | | [ranges::stride\_viewviews::stride](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/stride_view&action=edit&redlink=1 "cpp/ranges/stride view (page does not exist)") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") consisting of elements of another [`view`](../ranges/view "cpp/ranges/view"), advancing over N elements at a time (class template) (range adaptor object) | | [ranges::slide\_viewviews::slide](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/slide_view&action=edit&redlink=1 "cpp/ranges/slide view (page does not exist)") (C++23) | a [`view`](../ranges/view "cpp/ranges/view") whose Mth element is a [`view`](../ranges/view "cpp/ranges/view") over the Mth through (M + N - 1)th elements of another [`view`](../ranges/view "cpp/ranges/view") (class template) (range adaptor object) | | [ranges::chunk\_viewviews::chunk](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/chunk_view&action=edit&redlink=1 "cpp/ranges/chunk view (page does not exist)") (C++23) | a range of [`view`s](../ranges/view "cpp/ranges/view") that are `N`-sized non-overlapping successive chunks of the elements of another [`view`](../ranges/view "cpp/ranges/view") (class template) (range adaptor object) | | [ranges::chunk\_by\_viewviews::chunk\_by](https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/chunk_by_view&action=edit&redlink=1 "cpp/ranges/chunk by view (page does not exist)") (C++23) | splits the [`view`](../ranges/view "cpp/ranges/view") into subranges between each pair of adjacent elements for which the given predicate returns `false` (class template) (range adaptor object) | | Customization point objects | | Range access | | Defined in namespace `std::ranges` | | [ranges::begin](../ranges/begin "cpp/ranges/begin") (C++20) | returns an iterator to the beginning of a range (customization point object) | | [ranges::end](../ranges/end "cpp/ranges/end") (C++20) | returns a sentinel indicating the end 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) | | [ranges::cend](../ranges/cend "cpp/ranges/cend") (C++20) | returns a sentinel indicating the end of a read-only range (customization point object) | | [ranges::rbegin](../ranges/rbegin "cpp/ranges/rbegin") (C++20) | returns a reverse iterator to a range (customization point object) | | [ranges::rend](../ranges/rend "cpp/ranges/rend") (C++20) | returns a reverse end 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) | | [ranges::crend](../ranges/crend "cpp/ranges/crend") (C++20) | returns a reverse end iterator to a read-only range (customization point object) | | [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) | | [ranges::empty](../ranges/empty "cpp/ranges/empty") (C++20) | checks whether a range is empty (customization point object) | | [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) | | Enumerations | | Defined in namespace `std::ranges` | | [ranges::subrange\_kind](../ranges/subrange_kind "cpp/ranges/subrange kind") (C++20) | specifies whether a `[std::ranges::subrange](../ranges/subrange "cpp/ranges/subrange")` models `[std::ranges::sized\_range](../ranges/sized_range "cpp/ranges/sized range")` (enum) | | Helpers | | [std::tuple\_size<std::ranges::subrange>](../ranges/subrange/tuple_size "cpp/ranges/subrange/tuple size") (C++20) | obtains the number of components of a `[std::ranges::subrange](../ranges/subrange "cpp/ranges/subrange")` (class template specialization) | | [std::tuple\_element<std::ranges::subrange>](../ranges/subrange/tuple_element "cpp/ranges/subrange/tuple element") (C++20) | obtains the type of the iterator or the sentinel of a `[std::ranges::subrange](../ranges/subrange "cpp/ranges/subrange")` (class template specialization) | | [from\_range\_tfrom\_range](../ranges/from_range "cpp/ranges/from range") (C++23) | from-range construction tag (class) (constant) | ### Synopsis ``` #include <compare> #include <initializer_list> #include <iterator> namespace std::ranges { inline namespace /* unspecified */ { // range access inline constexpr /* unspecified */ begin = /* unspecified */; inline constexpr /* unspecified */ end = /* unspecified */; inline constexpr /* unspecified */ cbegin = /* unspecified */; inline constexpr /* unspecified */ cend = /* unspecified */; inline constexpr /* unspecified */ rbegin = /* unspecified */; inline constexpr /* unspecified */ rend = /* unspecified */; inline constexpr /* unspecified */ crbegin = /* unspecified */; inline constexpr /* unspecified */ crend = /* unspecified */; inline constexpr /* unspecified */ size = /* unspecified */; inline constexpr /* unspecified */ ssize = /* unspecified */; inline constexpr /* unspecified */ empty = /* unspecified */; inline constexpr /* unspecified */ data = /* unspecified */; inline constexpr /* unspecified */ cdata = /* unspecified */; } // ranges template<class T> concept range = /* see description */; template<class T> inline constexpr bool enable_borrowed_range = false; template<class T> concept borrowed_range = /* see description */; template<class T> using iterator_t = decltype(ranges::begin(declval<T&>())); template<range R> using sentinel_t = decltype(ranges::end(declval<R&>())); template<range R> using const_iterator_t = const_iterator<iterator_t<R>>; template<range R> using range_difference_t = iter_difference_t<iterator_t<R>>; template<sized_range R> using range_size_t = decltype(ranges::size(declval<R&>())); template<range R> using range_value_t = iter_value_t<iterator_t<R>>; template<range R> using range_reference_t = iter_reference_t<iterator_t<R>>; template<range R> using range_const_reference_t = iter_const_reference_t<iterator_t<R>>; template<range R> using range_rvalue_reference_t = iter_rvalue_reference_t<iterator_t<R>>; // sized ranges template<class> inline constexpr bool disable_sized_range = false; template<class T> concept sized_range = /* see description */; // views template<class T> inline constexpr bool enable_view = /* see description */; struct view_base {}; template<class T> concept view = /* see description */; // other range refinements template<class R, class T> concept output_range = /* see description */; template<class T> concept input_range = /* see description */; template<class T> concept forward_range = /* see description */; template<class T> concept bidirectional_range = /* see description */; template<class T> concept random_access_range = /* see description */; template<class T> concept contiguous_range = /* see description */; template<class T> concept common_range = /* see description */; template<class T> concept viewable_range = /* see description */; template<class T> concept constant_range = /* see description */; // class template view_interface template<class D> requires is_class_v<D> && same_as<D, remove_cv_t<D>> class view_interface; // sub-ranges enum class subrange_kind : bool { unsized, sized }; template<input_or_output_iterator I, sentinel_for<I> S = I, subrange_kind K = /* see description */> requires (K == subrange_kind::sized || !sized_sentinel_for<S, I>) class subrange; template<class I, class S, subrange_kind K> inline constexpr bool enable_borrowed_range<subrange<I, S, K>> = true; // dangling iterator handling struct dangling; // class template elements_of template<range R, class Allocator = allocator<byte>> struct elements_of; template<range R> using borrowed_iterator_t = /* see description */; template<range R> using borrowed_subrange_t = /* see description */; // range conversions template<class C, input_range R, class... Args> requires (!view<C>) constexpr C to(R&& r, Args&&... args); template<template<class...> class C, input_range R, class... Args> constexpr auto to(R&& r, Args&&... args); template<class C, class... Args> requires (!view<C>) constexpr auto to(Args&&... args); template<template<class...> class C, class... Args> constexpr auto to(Args&&... args); // empty view template<class T> requires is_object_v<T> class empty_view; template<class T> inline constexpr bool enable_borrowed_range<empty_view<T>> = true; namespace views { template<class T> inline constexpr empty_view<T> empty{}; } // single view template<move_constructible T> requires is_object_v<T> class single_view; namespace views { inline constexpr /* unspecified */ single = /* unspecified */; } template<bool Const, class T> using __maybe_const = conditional_t<Const, const T, T>; // exposition only // iota view template<weakly_incrementable W, semiregular Bound = unreachable_sentinel_t> requires __weakly_equality_comparable_with<W, Bound> && copyable<W> class iota_view; template<class W, class Bound> inline constexpr bool enable_borrowed_range<iota_view<W, Bound>> = true; namespace views { inline constexpr /* unspecified */ iota = /* unspecified */; } // repeat view template<move_constructible W, semiregular Bound = unreachable_sentinel_t> requires (is_object_v<W> && same_as<W, remove_cv_t<W>> && (__is_integer_like<Bound> || same_as<Bound, unreachable_sentinel_t>)) class repeat_view; namespace views { inline constexpr /* unspecified */ repeat = /* unspecified */; } // istream view template<movable Val, class CharT, class Traits = char_traits<CharT>> requires /* see description */ class basic_istream_view; template<class Val> using istream_view = basic_istream_view<Val, char>; template<class Val> using wistream_view = basic_istream_view<Val, wchar_t>; namespace views { template<class T> inline constexpr /* unspecified */ istream = /* unspecified */; } // range adaptor objects template<class D> requires is_class_v<D> && same_as<D, remove_cv_t<D>> class range_adaptor_closure { }; // all view namespace views { inline constexpr /* unspecified */ all = /* unspecified */; template<viewable_range R> using all_t = decltype(all(declval<R>())); } // ref view template<range R> requires is_object_v<R> class ref_view; template<class T> inline constexpr bool enable_borrowed_range<ref_view<T>> = true; // owning view template<range R> requires /* see description */ class owning_view; template<class T> inline constexpr bool enable_borrowed_range<owning_view<T>> = enable_borrowed_range<T>; // as rvalue view template<view V> requires input_range<V> class as_rvalue_view; template<class T> inline constexpr bool enable_borrowed_range<as_rvalue_view<T>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ as_rvalue = /* unspecified */; } // filter view template<input_range V, indirect_unary_predicate<iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class filter_view; namespace views { inline constexpr /* unspecified */ filter = /* unspecified */; } // transform view template<input_range V, move_constructible F> requires view<V> && is_object_v<F> && regular_invocable<F&, range_reference_t<V>> && __can_reference<invoke_result_t<F&, range_reference_t<V>>> class transform_view; namespace views { inline constexpr /* unspecified */ transform = /* unspecified */; } // take view template<view> class take_view; template<class T> inline constexpr bool enable_borrowed_range<take_view<T>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ take = /* unspecified */; } // take while view template<view V, class Pred> requires input_range<V> && is_object_v<Pred> && indirect_unary_predicate<const Pred, iterator_t<V>> class take_while_view; namespace views { inline constexpr /* unspecified */ take_while = /* unspecified */; } // drop view template<view V> class drop_view; template<class T> inline constexpr bool enable_borrowed_range<drop_view<T>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ drop = /* unspecified */; } // drop while view template<view V, class Pred> requires input_range<V> && is_object_v<Pred> && indirect_unary_predicate<const Pred, iterator_t<V>> class drop_while_view; template<class T, class Pred> inline constexpr bool enable_borrowed_range<drop_while_view<T, Pred>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ drop_while = /* unspecified */; } // join view template<input_range V> requires view<V> && input_range<range_reference_t<V>> class join_view; namespace views { inline constexpr /* unspecified */ join = /* unspecified */; } // join with view template<class R, class P> concept __compatible_joinable_ranges = /* see description */; // exposition only template<input_range V, forward_range Pattern> requires view<V> && input_range<range_reference_t<V>> && view<Pattern> && __compatible_joinable_ranges<range_reference_t<V>, Pattern> class join_with_view; namespace views { inline constexpr /* unspecified */ join_with = /* unspecified */; } // lazy split view template<class R> concept __tiny_range = /* see description */; // exposition only template<input_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> && (forward_range<V> || __tiny_range<Pattern>) class lazy_split_view; // split view template<forward_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> class split_view; namespace views { inline constexpr /* unspecified */ lazy_split = /* unspecified */; inline constexpr /* unspecified */ split = /* unspecified */; } // counted view namespace views { inline constexpr /* unspecified */ counted = /* unspecified */; } // common view template<view V> requires (!common_range<V> && copyable<iterator_t<V>>) class common_view; template<class T> inline constexpr bool enable_borrowed_range<common_view<T>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ common = /* unspecified */; } // reverse view template<view V> requires bidirectional_range<V> class reverse_view; template<class T> inline constexpr bool enable_borrowed_range<reverse_view<T>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ reverse = /* unspecified */; } // as const view template<input_range R> constexpr auto& __possibly_const_range(R& r) { // exposition only if constexpr (constant_range<const R> && !constant_range<R>) { return const_cast<const R&>(r); } else { return r; } } template<view V> requires input_range<V> class as_const_view; template<class T> inline constexpr bool enable_borrowed_range<as_const_view<T>> = enable_borrowed_range<T>; namespace views { inline constexpr /* unspecified */ as_const = /* unspecified */; } // elements view template<input_range V, size_t N> requires /* see description */ class elements_view; template<class T, size_t N> inline constexpr bool enable_borrowed_range<elements_view<T, N>> = enable_borrowed_range<T>; template<class R> using keys_view = elements_view<R, 0>; template<class R> using values_view = elements_view<R, 1>; namespace views { template<size_t N> inline constexpr /* unspecified */ elements = /* unspecified */; inline constexpr auto keys = elements<0>; inline constexpr auto values = elements<1>; } // zip view template<input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) class zip_view; template<class... Views> inline constexpr bool enable_borrowed_range<zip_view<Views...>> = (enable_borrowed_range<Views> && ...); namespace views { inline constexpr /* unspecified */ zip = /* unspecified */; } // zip transform view template<move_constructible F, input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) && is_object_v<F> && regular_invocable<F&, range_reference_t<Views>...> && __can_reference<invoke_result_t<F&, range_reference_t<Views>...>> class zip_transform_view; namespace views { inline constexpr /* unspecified */ zip_transform = /* unspecified */; } // adjacent view template<forward_range V, size_t N> requires view<V> && (N > 0) class adjacent_view; template<class V, size_t N> inline constexpr bool enable_borrowed_range<adjacent_view<V, N>> = enable_borrowed_range<V>; namespace views { template<size_t N> inline constexpr /* unspecified */ adjacent = /* unspecified */; inline constexpr auto pairwise = adjacent<2>; } // adjacent transform view template<forward_range V, move_constructible F, size_t N> requires /* see description */ class adjacent_transform_view; namespace views { template<size_t N> inline constexpr /* unspecified */ adjacent_transform = /* unspecified */; inline constexpr auto pairwise_transform = adjacent_transform<2>; } // chunk view template<view V> requires input_range<V> class chunk_view; template<view V> requires forward_range<V> class chunk_view<V>; template<class V> inline constexpr bool enable_borrowed_range<chunk_view<V>> = forward_range<V> && enable_borrowed_range<V>; namespace views { inline constexpr /* unspecified */ chunk = /* unspecified */; } // slide view template<forward_range V> requires view<V> class slide_view; template<class V> inline constexpr bool enable_borrowed_range<slide_view<V>> = enable_borrowed_range<V>; namespace views { inline constexpr /* unspecified */ slide = /* unspecified */; } // chunk by view template<forward_range V, indirect_binary_predicate<iterator_t<V>, iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class chunk_by_view; namespace views { inline constexpr /* unspecified */ chunk_by = /* unspecified */; } // stride view template<input_range V> requires view<V> class stride_view; template<class V> inline constexpr bool enable_borrowed_range<stride_view<V>> = enable_borrowed_range<V>; namespace views { inline constexpr /* unspecified */ stride = /* unspecified */; } // cartesian product view template<input_range First, forward_range... Vs> requires (view<First> && ... && view<Vs>) class cartesian_product_view; namespace views { inline constexpr /* unspecified */ cartesian_product = /* unspecified */; } } namespace std { namespace views = ranges::views; template<class T> struct tuple_size; template<size_t I, class T> struct tuple_element; template<class I, class S, ranges::subrange_kind K> struct tuple_size<ranges::subrange<I, S, K>> : integral_constant<size_t, 2> {}; template<class I, class S, ranges::subrange_kind K> struct tuple_element<0, ranges::subrange<I, S, K>> { using type = I; }; template<class I, class S, ranges::subrange_kind K> struct tuple_element<1, ranges::subrange<I, S, K>> { using type = S; }; template<class I, class S, ranges::subrange_kind K> struct tuple_element<0, const ranges::subrange<I, S, K>> { using type = I; }; template<class I, class S, ranges::subrange_kind K> struct tuple_element<1, const ranges::subrange<I, S, K>> { using type = S; }; struct from_range_t { explicit from_range_t() = default; }; inline constexpr from_range_t from_range{}; } ``` #### Concept [`range`](../ranges/range "cpp/ranges/range") ``` namespace std::ranges { template< class T > concept range = requires(T& t) { ranges::begin(t); // equality-preserving for forward iterators ranges::end(t); }; } ``` #### Concept [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") ``` namespace std::ranges { template<class T> concept borrowed_range = range<T> && (is_lvalue_reference_v<T> || enable_borrowed_range<remove_cvref_t<T>>); } ``` #### Concept [`sized_range`](../ranges/sized_range "cpp/ranges/sized range") ``` namespace std::ranges { template< class T > concept sized_range = range<T> && requires(T& t) { ranges::size(t); }; } ``` #### Concept [`view`](../ranges/view "cpp/ranges/view") ``` namespace std::ranges { template<class T> inline constexpr bool enable_view = derived_from<T, view_base>; template<class T> concept view = range<T> && movable<T> && enable_view<T>; } ``` #### Concept [`output_range`](../ranges/output_range "cpp/ranges/output range") ``` namespace std::ranges { template<class R, class T> concept output_range = range<R> && output_iterator<iterator_t<R>, T>; } ``` #### Concept [`input_range`](../ranges/input_range "cpp/ranges/input range") ``` namespace std::ranges { template<class T> concept input_range = range<T> && input_iterator<iterator_t<T>>; } ``` #### Concept [`forward_range`](../ranges/forward_range "cpp/ranges/forward range") ``` namespace std::ranges { template<class T> concept forward_range = input_range<T> && forward_iterator<iterator_t<T>>; } ``` #### Concept [`bidirectional_range`](../ranges/bidirectional_range "cpp/ranges/bidirectional range") ``` namespace std::ranges { template<class T> concept bidirectional_range = forward_range<T> && bidirectional_iterator<iterator_t<T>>; } ``` #### Concept [`random_access_range`](../ranges/random_access_range "cpp/ranges/random access range") ``` namespace std::ranges { template<class T> concept random_access_range = bidirectional_range<T> && random_access_iterator<iterator_t<T>>; } ``` #### Concept [`contiguous_range`](../ranges/contiguous_range "cpp/ranges/contiguous range") ``` namespace std::ranges { template<class T> concept contiguous_range = random_access_range<T> && contiguous_iterator<iterator_t<T>> && requires(T& t) { { ranges::data(t) } -> same_as<add_pointer_t<range_reference_t<T>>>; }; } ``` #### Concept [`common_range`](../ranges/common_range "cpp/ranges/common range") ``` namespace std::ranges { template<class T> concept common_range = range<T> && same_as<iterator_t<T>, sentinel_t<T>>; } ``` #### Concept [`viewable_range`](../ranges/viewable_range "cpp/ranges/viewable range") ``` namespace std::ranges { template<class T> concept viewable_range = range<T> && (borrowed_range<T> || view<remove_cvref_t<T>>); } ``` #### Helper concepts Note: The following names are only for exposition, they are not part of the interface. ``` namespace std::ranges { // unspecified, for name lookup only template<class R> concept /*simple-view*/ = // exposition only view<R> && range<const R> && same_as<iterator_t<R>, iterator_t<const R>> && same_as<sentinel_t<R>, sentinel_t<const R>>; template<class I> concept /*has-arrow*/ = // exposition only input_iterator<I> && (is_pointer_v<I> || requires(I i) { i.operator->(); }); template<class T, class U> concept /*different-from*/ = // exposition only !same_as<remove_cvref_t<T>, remove_cvref_t<U>>; template<class I> concept /*decrementable*/ = // exposition only incrementable<I> && requires(I i) { { --i } -> same_as<I&>; { i-- } -> same_as<I>; }; template<class I> concept /*advanceable*/ = // exposition only /*decrementable*/<I> && totally_ordered<I> && requires(I i, const I j, const iter_difference_t<I> n) { { i += n } -> same_as<I&>; { i -= n } -> same_as<I&>; I { j + n }; I { n + j }; I { j - n }; { j - j } -> convertible_to<iter_difference_t<I>>; }; } ``` #### Class template `std::ranges::view_interface` ``` namespace std::ranges { template<class D> requires is_class_v<D> && same_as<D, remove_cv_t<D>> class view_interface { private: constexpr D& derived() noexcept { // exposition only return static_cast<D&>(*this); } constexpr const D& derived() const noexcept { // exposition only return static_cast<const D&>(*this); } public: constexpr bool empty() requires forward_range<D> { return ranges::begin(derived()) == ranges::end(derived()); } constexpr bool empty() const requires forward_range<const D> { return ranges::begin(derived()) == ranges::end(derived()); } constexpr explicit operator bool() requires requires { ranges::empty(derived()); } { return !ranges::empty(derived()); } constexpr explicit operator bool() const requires requires { ranges::empty(derived()); } { return !ranges::empty(derived()); } constexpr auto data() requires contiguous_iterator<iterator_t<D>> { return to_address(ranges::begin(derived())); } constexpr auto data() const requires range<const D> && contiguous_iterator<iterator_t<const D>> { return to_address(ranges::begin(derived())); } constexpr auto size() requires forward_range<D> && sized_sentinel_for<sentinel_t<D>, iterator_t<D>> { return ranges::end(derived()) - ranges::begin(derived()); } constexpr auto size() const requires forward_range<const D> && sized_sentinel_for<sentinel_t<const D>, iterator_t<const D>> { return ranges::end(derived()) - ranges::begin(derived()); } constexpr decltype(auto) front() requires forward_range<D>; constexpr decltype(auto) front() const requires forward_range<const D>; constexpr decltype(auto) back() requires bidirectional_range<D> && common_range<D>; constexpr decltype(auto) back() const requires bidirectional_range<const D> && common_range<const D>; template<random_access_range R = D> constexpr decltype(auto) operator[](range_difference_t<R> n) { return ranges::begin(derived())[n]; } template<random_access_range R = const D> constexpr decltype(auto) operator[](range_difference_t<R> n) const { return ranges::begin(derived())[n]; } }; } ``` #### Class template `[std::ranges::subrange](../ranges/subrange "cpp/ranges/subrange")` ``` namespace std::ranges { template<class From, class To> concept /*uses-nonqualification-pointer-conversion*/ = // exposition only is_pointer_v<From> && is_pointer_v<To> && !convertible_to<remove_pointer_t<From>(*)[], remove_pointer_t<To>(*)[]>; template<class From, class To> concept /*convertible-to-non-slicing*/ = // exposition only convertible_to<From, To> && !/*uses-nonqualification-pointer-conversion*/<decay_t<From>, decay_t<To>>; template<class T> concept /*pair-like*/ = // exposition only !is_reference_v<T> && requires(T t) { typename tuple_size<T>::type; // ensures tuple_size<T> // is complete requires derived_from<tuple_size<T>, integral_constant<size_t, 2>>; typename tuple_element_t<0, remove_const_t<T>>; typename tuple_element_t<1, remove_const_t<T>>; { std::get<0>(t) } -> convertible_to<const tuple_element_t<0, T>&>; { std::get<1>(t) } -> convertible_to<const tuple_element_t<1, T>&>; }; template<class T, class U, class V> concept /*pair-like-convertible-from*/ = // exposition only !range<T> && /*pair-like*/<T> && constructible_from<T, U, V> && /*convertible-to-non-slicing*/<U, tuple_element_t<0, T>> && convertible_to<V, tuple_element_t<1, T>>; template<input_or_output_iterator I, sentinel_for<I> S = I, subrange_kind K = sized_sentinel_for<S, I> ? subrange_kind::sized : subrange_kind::unsized> requires (K == subrange_kind::sized || !sized_sentinel_for<S, I>) class subrange : public view_interface<subrange<I, S, K>> { private: static constexpr bool StoreSize = // exposition only K == subrange_kind::sized && !sized_sentinel_for<S, I>; I begin_ = I(); // exposition only S end_ = S(); // exposition only /*make-unsigned-like-t*/<iter_difference_t<I>> size_ = 0; // exposition only; // present only // when StoreSize is true public: subrange() requires default_initializable<I> = default; constexpr subrange(/*convertible-to-non-slicing*/<I> auto i, S s) requires (!StoreSize); constexpr subrange(/*convertible-to-non-slicing*/<I> auto i, S s, /*make-unsigned-like-t*/<iter_difference_t<I>> n) requires (K == subrange_kind::sized); template</*different-from*/<subrange> R> requires borrowed_range<R> && /*convertible-to-non-slicing*/<iterator_t<R>, I> && convertible_to<sentinel_t<R>, S> constexpr subrange(R&& r) requires (!StoreSize || sized_range<R>); template<borrowed_range R> requires /*convertible-to-non-slicing*/<iterator_t<R>, I> && convertible_to<sentinel_t<R>, S> constexpr subrange(R&& r, /*make-unsigned-like-t*/<iter_difference_t<I>> n) requires (K == subrange_kind::sized) : subrange{ranges::begin(r), ranges::end(r), n} {} template</*different-from*/<subrange> PairLike> requires /*pair-like-convertible-from*/<PairLike, const I&, const S&> constexpr operator PairLike() const; constexpr I begin() const requires copyable<I>; [[nodiscard]] constexpr I begin() requires (!copyable<I>); constexpr S end() const; constexpr bool empty() const; constexpr /*make-unsigned-like-t*/<iter_difference_t<I>> size() const requires (K == subrange_kind::sized); [[nodiscard]] constexpr subrange next(iter_difference_t<I> n = 1) const & requires forward_iterator<I>; [[nodiscard]] constexpr subrange next(iter_difference_t<I> n = 1) &&; [[nodiscard]] constexpr subrange prev(iter_difference_t<I> n = 1) const requires bidirectional_iterator<I>; constexpr subrange& advance(iter_difference_t<I> n); }; template<input_or_output_iterator I, sentinel_for<I> S> subrange(I, S) -> subrange<I, S>; template<input_or_output_iterator I, sentinel_for<I> S> subrange(I, S, /*make-unsigned-like-t*/<iter_difference_t<I>>) -> subrange<I, S, subrange_kind::sized>; template<borrowed_range R> subrange(R&&) -> subrange<iterator_t<R>, sentinel_t<R>, (sized_range<R> || sized_sentinel_for<sentinel_t<R>, iterator_t<R>>) ? subrange_kind::sized : subrange_kind::unsized>; template<borrowed_range R> subrange(R&&, /*make-unsigned-like-t*/<range_difference_t<R>>) -> subrange<iterator_t<R>, sentinel_t<R>, subrange_kind::sized>; template<size_t N, class I, class S, subrange_kind K> requires ((N == 0 && copyable<I>) || N == 1) constexpr auto get(const subrange<I, S, K>& r); template<size_t N, class I, class S, subrange_kind K> requires (N < 2) constexpr auto get(subrange<I, S, K>&& r); } namespace std { using ranges::get; } ``` #### Class `[std::ranges::dangling](../ranges/dangling "cpp/ranges/dangling")` ``` namespace std::ranges { struct dangling { constexpr dangling() noexcept = default; constexpr dangling(auto&&...) noexcept {} }; } ``` #### Class template `[std::ranges::empty\_view](../ranges/empty_view "cpp/ranges/empty view")` ``` namespace std::ranges { template<class T> requires is_object_v<T> class empty_view : public view_interface<empty_view<T>> { public: static constexpr T* begin() noexcept { return nullptr; } static constexpr T* end() noexcept { return nullptr; } static constexpr T* data() noexcept { return nullptr; } static constexpr size_t size() noexcept { return 0; } static constexpr bool empty() noexcept { return true; } }; } ``` #### Class template `std::ranges::single_view` ``` namespace std::ranges { template<copy_constructible T> requires is_object_v<T> class single_view : public view_interface<single_view<T>> { private: /*copyable-box*/<T> value_; // exposition only public: single_view() requires default_initializable<T> = default; constexpr explicit single_view(const T& t); constexpr explicit single_view(T&& t); template<class... Args> requires constructible_from<T, Args...> constexpr explicit single_view(in_place_t, Args&&... args); constexpr T* begin() noexcept; constexpr const T* begin() const noexcept; constexpr T* end() noexcept; constexpr const T* end() const noexcept; static constexpr size_t size() noexcept; constexpr T* data() noexcept; constexpr const T* data() const noexcept; }; template<class T> single_view(T) -> single_view<T>; } ``` #### Class template `[std::ranges::iota\_view](../ranges/iota_view "cpp/ranges/iota view")` ``` namespace std::ranges { template<class I> concept decrementable = /* see description */; // exposition only template<class I> concept advanceable = /* see description */; // exposition only template<weakly_incrementable W, semiregular Bound = unreachable_sentinel_t> requires /*weakly-equality-comparable-with*/<W, Bound> && copyable<W> class iota_view : public view_interface<iota_view<W, Bound>> { private: // class iota_view::iterator struct iterator; // exposition only // class iota_view::sentinel struct sentinel; // exposition only W value_ = W(); // exposition only Bound bound_ = Bound(); // exposition only public: iota_view() requires default_initializable<W> = default; constexpr explicit iota_view(W value); constexpr iota_view(type_identity_t<W> value, type_identity_t<Bound> bound); constexpr iota_view(iterator first, /* see description */ last); constexpr iterator begin() const; constexpr auto end() const; constexpr iterator end() const requires same_as<W, Bound>; constexpr auto size() const requires /* see description */; }; template<class W, class Bound> requires (!/*is-integer-like*/<W> || !/*is-integer-like*/<Bound> || (/*is-signed-integer-like*/<W> == /*is-signed-integer-like*/<Bound>)) iota_view(W, Bound) -> iota_view<W, Bound>; } ``` #### Class template `std::ranges::iota_view::iterator` ``` namespace std::ranges { template<weakly_incrementable W, semiregular Bound> requires /*weakly-equality-comparable-with*/<W, Bound> && copyable<W> struct iota_view<W, Bound>::iterator { private: W value_ = W(); // exposition only public: using iterator_concept = /* see description */; using iterator_category = input_iterator_tag; // present only if W models incrementable using value_type = W; using difference_type = /*IOTA-DIFF-T*/(W); iterator() requires default_initializable<W> = default; constexpr explicit iterator(W value); constexpr W operator*() const noexcept(is_nothrow_copy_constructible_v<W>); constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires incrementable<W>; constexpr iterator& operator--() requires /*decrementable*/<W>; constexpr iterator operator--(int) requires /*decrementable*/<W>; constexpr iterator& operator+=(difference_type n) requires /*advanceable*/<W>; constexpr iterator& operator-=(difference_type n) requires /*advanceable*/<W>; constexpr W operator[](difference_type n) const requires /*advanceable*/<W>; friend constexpr bool operator==(const iterator& x, const iterator& y) requires equality_comparable<W>; friend constexpr bool operator<(const iterator& x, const iterator& y) requires totally_ordered<W>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires totally_ordered<W>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires totally_ordered<W>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires totally_ordered<W>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires totally_ordered<W> && three_way_comparable<W>; friend constexpr iterator operator+(iterator i, difference_type n) requires /*advanceable*/<W>; friend constexpr iterator operator+(difference_type n, iterator i) requires /*advanceable*/<W>; friend constexpr iterator operator-(iterator i, difference_type n) requires /*advanceable*/<W>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires /*advanceable*/<W>; }; } ``` #### Class template `std::ranges::iota_view::sentinel` ``` namespace std::ranges { template<weakly_incrementable W, semiregular Bound> requires /*weakly-equality-comparable-with*/<W, Bound> && copyable<W> struct iota_view<W, Bound>::sentinel { private: Bound bound_ = Bound(); // exposition only public: sentinel() = default; constexpr explicit sentinel(Bound bound); friend constexpr bool operator==(const iterator& x, const sentinel& y); friend constexpr iter_difference_t<W> operator-(const iterator& x, const sentinel& y) requires sized_sentinel_for<Bound, W>; friend constexpr iter_difference_t<W> operator-(const sentinel& x, const iterator& y) requires sized_sentinel_for<Bound, W>; }; } ``` #### Class template `std::ranges::repeat_view` ``` namespace std::ranges { template<copy_constructible W, semiregular Bound = unreachable_sentinel_t> requires (is_object_v<W> && same_as<W, remove_cv_t<W>> && (/*is-integer-like*/<Bound> || same_as<Bound, unreachable_sentinel_t>)) class repeat_view : public view_interface<repeat_view<W, Bound>> { private: // class range_view::iterator struct iterator; /*copyable-box*/<W> value_ = W(); // exposition only Bound bound_ = Bound(); // exposition only public: repeat_view() requires default_initializable<W> = default; constexpr explicit repeat_view(const W& value, Bound bound = Bound()); constexpr explicit repeat_view(W&& value, Bound bound = Bound()); template<class... WArgs, class... BoundArgs> requires constructible_from<W, WArgs...> && constructible_from<Bound, BoundArgs...> constexpr explicit repeat_view(piecewise_construct_t, tuple<WArgs...> value_args, tuple<BoundArgs...> bound_args = tuple<>{}); constexpr iterator begin() const; constexpr iterator end() const requires (!same_as<Bound, unreachable_sentinel_t>); constexpr unreachable_sentinel_t end() const noexcept; constexpr auto size() const requires (!same_as<Bound, unreachable_sentinel_t>); }; template<class W, class Bound> repeat_view(W, Bound) -> repeat_view<W, Bound>; } ``` #### Class template `std::ranges::repeat_view::iterator` ``` namespace std::ranges { template<copy_constructible W, semiregular Bound = unreachable_sentinel_t> requires /*is-integer-like*/<Bound> || same_as<Bound, unreachable_sentinel_t> class repeat_view<W, Bound>::iterator { private: using /*index-type*/ = // exposition only conditional_t<same_as<Bound, unreachable_sentinel_t>, ptrdiff_t, Bound >; const W* value_ = nullptr; // exposition only /*index-type*/ current_ = /*index-type*/(); // exposition only // exposition only constexpr explicit iterator(const W * value, /*index-type*/ b = /*index-type*/()); public: using iterator_concept = random_access_iterator_tag; using iterator_category = random_access_iterator_tag; using value_type = W; using difference_type = conditional_t</*is-signed-like*/</*index-type*/>, /*index-type*/, /*IOTA-DIFF-T*/(/*index-type*/) >; iterator() = default; constexpr const W& operator*() const noexcept; constexpr iterator& operator++(); constexpr iterator operator++(int); constexpr iterator& operator--(); constexpr iterator operator--(int); constexpr iterator& operator+=(difference_type n); constexpr iterator& operator-=(difference_type n); constexpr const W& operator[](difference_type n) const noexcept; friend constexpr bool operator==(const iterator& x, const iterator& y); friend constexpr auto operator<=>(const iterator& x, const iterator& y); friend constexpr iterator operator+(iterator i, difference_type n); friend constexpr iterator operator+(difference_type n, iterator i); friend constexpr iterator operator-(iterator i, difference_type n); friend constexpr difference_type operator-(const iterator& x, const iterator& y); }; } ``` #### Class template `std::ranges::basic_istream_view` ``` namespace std::ranges { template<class Val, class CharT, class Traits> concept /*stream-extractable*/ = // exposition only requires(basic_istream<CharT, Traits>& is, Val& t) { is >> t; }; template<movable Val, class CharT, class Traits = char_traits<CharT>> requires default_initializable<Val> && /*stream-extractable*/<Val, CharT, Traits> class basic_istream_view : public view_interface<basic_istream_view<Val, CharT, Traits>> { public: constexpr explicit basic_istream_view(basic_istream<CharT, Traits>& stream); constexpr auto begin() { *stream_ >> value_; return iterator{*this}; } constexpr default_sentinel_t end() const noexcept; private: struct iterator; // exposition only basic_istream<CharT, Traits>* stream_; // exposition only Val value_ = Val(); // exposition only }; } ``` #### Class template `std::ranges::basic_istream_view::iterator` ``` namespace std::ranges { template<movable Val, class CharT, class Traits> requires default_initializable<Val> && /*stream-extractable*/<Val, CharT, Traits> class basic_istream_view<Val, CharT, Traits>::iterator { public: using iterator_concept = input_iterator_tag; using difference_type = ptrdiff_t; using value_type = Val; constexpr explicit iterator(basic_istream_view& parent) noexcept; iterator(const iterator&) = delete; iterator(iterator&&) = default; iterator& operator=(const iterator&) = delete; iterator& operator=(iterator&&) = default; iterator& operator++(); void operator++(int); Val& operator*() const; friend bool operator==(const iterator& x, default_sentinel_t); private: basic_istream_view* parent_; // exposition only }; } ``` #### Class template `[std::ranges::ref\_view](../ranges/ref_view "cpp/ranges/ref view")` ``` namespace std::ranges { template<range R> requires is_object_v<R> class ref_view : public view_interface<ref_view<R>> { private: R* r_; // exposition only public: template</*different-from*/<ref_view> T> requires /* see description */ constexpr ref_view(T&& t); constexpr R& base() const { return *r_; } constexpr iterator_t<R> begin() const { return ranges::begin(*r_); } constexpr sentinel_t<R> end() const { return ranges::end(*r_); } constexpr bool empty() const requires requires { ranges::empty(*r_); } { return ranges::empty(*r_); } constexpr auto size() const requires sized_range<R> { return ranges::size(*r_); } constexpr auto data() const requires contiguous_range<R> { return ranges::data(*r_); } }; template<class R> ref_view(R&) -> ref_view<R>; } ``` #### Class template `std::ranges::owning_view` ``` namespace std::ranges { template<range R> requires movable<R> && (!/*is-initializer-list*/<R>) class owning_view : public view_interface<owning_view<R>> { private: R r_ = R(); // exposition only public: owning_view() requires default_initializable<R> = default; constexpr owning_view(R&& t); owning_view(owning_view&&) = default; owning_view& operator=(owning_view&&) = default; constexpr R& base() & noexcept { return r_; } constexpr const R& base() const& noexcept { return r_; } constexpr R&& base() && noexcept { return std::move(r_); } constexpr const R&& base() const&& noexcept { return std::move(r_); } constexpr iterator_t<R> begin() { return ranges::begin(r_); } constexpr sentinel_t<R> end() { return ranges::end(r_); } constexpr auto begin() const requires range<const R> { return ranges::begin(r_); } constexpr auto end() const requires range<const R> { return ranges::end(r_); } constexpr bool empty() requires requires { ranges::empty(r_); } { return ranges::empty(r_); } constexpr bool empty() const requires requires { ranges::empty(r_); } { return ranges::empty(r_); } constexpr auto size() requires sized_range<R> { return ranges::size(r_); } constexpr auto size() const requires sized_range<const R> { return ranges::size(r_); } constexpr auto data() requires contiguous_range<R> { return ranges::data(r_); } constexpr auto data() const requires contiguous_range<const R> { return ranges::data(r_); } }; } ``` #### Class template `[std::ranges::filter\_view](../ranges/filter_view "cpp/ranges/filter view")` ``` namespace std::ranges { template<input_range V, indirect_unary_predicate<iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class filter_view : public view_interface<filter_view<V, Pred>> { private: V base_ = V(); // exposition only /*copyable-box*/<Pred> pred_; // exposition only // class filter_view::iterator class iterator; // exposition only // class filter_view::sentinel class sentinel; // exposition only public: filter_view() requires default_initializable<V> && default_initializable<Pred> = default; constexpr filter_view(V base, Pred pred); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr const Pred& pred() const; constexpr iterator begin(); constexpr auto end() { if constexpr (common_range<V>) return iterator{*this, ranges::end(base_)}; else return sentinel{*this}; } }; template<class R, class Pred> filter_view(R&&, Pred) -> filter_view<views::all_t<R>, Pred>; } ``` #### Class template `std::ranges::filter_view::iterator` ``` namespace std::ranges { template<input_range V, indirect_unary_predicate<iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class filter_view<V, Pred>::iterator { private: iterator_t<V> current_ = iterator_t<V>(); // exposition only filter_view* parent_ = nullptr; // exposition only public: using iterator_concept = /* see description */; using iterator_category = /* see description */; // not always present using value_type = range_value_t<V>; using difference_type = range_difference_t<V>; iterator() requires default_initializable<iterator_t<V>> = default; constexpr iterator(filter_view& parent, iterator_t<V> current); constexpr const iterator_t<V>& base() const & noexcept; constexpr iterator_t<V> base() &&; constexpr range_reference_t<V> operator*() const; constexpr iterator_t<V> operator->() const requires /*has-arrow*/<iterator_t<V>> && copyable<iterator_t<V>>; constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires forward_range<V>; constexpr iterator& operator--() requires bidirectional_range<V>; constexpr iterator operator--(int) requires bidirectional_range<V>; friend constexpr bool operator==(const iterator& x, const iterator& y) requires equality_comparable<iterator_t<V>>; friend constexpr range_rvalue_reference_t<V> iter_move(const iterator& i) noexcept(noexcept(ranges::iter_move(i.current_))); friend constexpr void iter_swap(const iterator& x, const iterator& y) noexcept(noexcept(ranges::iter_swap(x.current_, y.current_))) requires indirectly_swappable<iterator_t<V>>; }; } ``` #### Class template `std::ranges::filter_view::sentinel` ``` namespace std::ranges { template<input_range V, indirect_unary_predicate<iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class filter_view<V, Pred>::sentinel { private: sentinel_t<V> end_ = sentinel_t<V>(); // exposition only public: sentinel() = default; constexpr explicit sentinel(filter_view& parent); constexpr sentinel_t<V> base() const; friend constexpr bool operator==(const iterator& x, const sentinel& y); }; } ``` #### Class template `[std::ranges::transform\_view](../ranges/transform_view "cpp/ranges/transform view")` ``` namespace std::ranges { template<input_range V, copy_constructible F> requires view<V> && is_object_v<F> && regular_invocable<F&, range_reference_t<V>> && /*can-reference*/<invoke_result_t<F&, range_reference_t<V>>> class transform_view : public view_interface<transform_view<V, F>> { private: // class template transform_view::iterator template<bool> struct iterator; // exposition only // class template transform_view::sentinel template<bool> struct sentinel; // exposition only V base_ = V(); // exposition only /*copyable-box*/<F> fun_; // exposition only public: transform_view() requires default_initializable<V> && default_initializable<F> = default; constexpr transform_view(V base, F fun); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr iterator<false> begin(); constexpr iterator<true> begin() const requires range<const V> && regular_invocable<const F&, range_reference_t<const V>>; constexpr sentinel<false> end(); constexpr iterator<false> end() requires common_range<V>; constexpr sentinel<true> end() const requires range<const V> && regular_invocable<const F&, range_reference_t<const V>>; constexpr iterator<true> end() const requires common_range<const V> && regular_invocable<const F&, range_reference_t<const V>>; constexpr auto size() requires sized_range<V> { return ranges::size(base_); } constexpr auto size() const requires sized_range<const V> { return ranges::size(base_); } }; template<class R, class F> transform_view(R&&, F) -> transform_view<views::all_t<R>, F>; } ``` #### Class template `std::ranges::transform_view::iterator` ``` namespace std::ranges { template<input_range V, copy_constructible F> requires view<V> && is_object_v<F> && regular_invocable<F&, range_reference_t<V>> && /*can-reference*/<invoke_result_t<F&, range_reference_t<V>>> template<bool Const> class transform_view<V, F>::iterator { private: using Parent = /*maybe-const*/<Const, transform_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only iterator_t<Base> current_ = iterator_t<Base>(); // exposition only Parent* parent_ = nullptr; // exposition only public: using iterator_concept = /* see description */; using iterator_category = /* see description */; // not always present using value_type = remove_cvref_t<invoke_result_t<F&, range_reference_t<Base>>>; using difference_type = range_difference_t<Base>; iterator() requires default_initializable<iterator_t<Base>> = default; constexpr iterator(Parent& parent, iterator_t<Base> current); constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, iterator_t<Base>>; constexpr const iterator_t<Base>& base() const & noexcept; constexpr iterator_t<Base> base() &&; constexpr decltype(auto) operator*() const { return invoke(*parent_->fun_, *current_); } constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires forward_range<Base>; constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type n) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type n) requires random_access_range<Base>; constexpr decltype(auto) operator[](difference_type n) const requires random_access_range<Base> { return invoke(*parent_->fun_, current_[n]); } friend constexpr bool operator==(const iterator& x, const iterator& y) requires equality_comparable<iterator_t<Base>>; friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable<iterator_t<Base>>; friend constexpr iterator operator+(iterator i, difference_type n) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type n, iterator i) requires random_access_range<Base>; friend constexpr iterator operator-(iterator i, difference_type n) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for<iterator_t<Base>, iterator_t<Base>>; friend constexpr decltype(auto) iter_move(const iterator& i) noexcept(noexcept(invoke(*i.parent_->fun_, *i.current_))) { if constexpr (is_lvalue_reference_v<decltype(*i)>) return std::move(*i); else return *i; } }; } ``` #### Class template `std::ranges::transform_view::sentinel` ``` namespace std::ranges { template<input_range V, copy_constructible F> requires view<V> && is_object_v<F> && regular_invocable<F&, range_reference_t<V>> && /*can-reference*/<invoke_result_t<F&, range_reference_t<V>>> template<bool Const> class transform_view<V, F>::sentinel { private: using Parent = /*maybe-const*/<Const, transform_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only public: sentinel() = default; constexpr explicit sentinel(sentinel_t<Base> end); constexpr sentinel(sentinel<!Const> i) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; constexpr sentinel_t<Base> base() const; template<bool OtherConst> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, V>> operator-(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, V>> operator-(const sentinel& y, const iterator<OtherConst>& x); }; } ``` #### Class template `[std::ranges::take\_view](../ranges/take_view "cpp/ranges/take view")` ``` namespace std::ranges { template<view V> class take_view : public view_interface<take_view<V>> { private: V base_ = V(); // exposition only range_difference_t<V> count_ = 0; // exposition only // class template take_view::sentinel template<bool> struct sentinel; // exposition only public: take_view() requires default_initializable<V> = default; constexpr take_view(V base, range_difference_t<V> count); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() requires (!/*simple-view*/<V>) { if constexpr (sized_range<V>) { if constexpr (random_access_range<V>) { return ranges::begin(base_); } else { auto sz = range_difference_t<V>(size()); return counted_iterator(ranges::begin(base_), sz); } } else { return counted_iterator(ranges::begin(base_), count_); } } constexpr auto begin() const requires range<const V> { if constexpr (sized_range<const V>) { if constexpr (random_access_range<const V>) { return ranges::begin(base_); } else { auto sz = range_difference_t<const V>(size()); return counted_iterator(ranges::begin(base_), sz); } } else { return counted_iterator(ranges::begin(base_), count_); } } constexpr auto end() requires (!/*simple-view*/<V>) { if constexpr (sized_range<V>) { if constexpr (random_access_range<V>) return ranges::begin(base_) + range_difference_t<V>(size()); else return default_sentinel; } else { return sentinel<false>{ranges::end(base_)}; } } constexpr auto end() const requires range<const V> { if constexpr (sized_range<const V>) { if constexpr (random_access_range<const V>) return ranges::begin(base_) + range_difference_t<const V>(size()); else return default_sentinel; } else { return sentinel<true>{ranges::end(base_)}; } } constexpr auto size() requires sized_range<V> { auto n = ranges::size(base_); return ranges::min(n, static_cast<decltype(n)>(count_)); } constexpr auto size() const requires sized_range<const V> { auto n = ranges::size(base_); return ranges::min(n, static_cast<decltype(n)>(count_)); } }; template<class R> take_view(R&&, range_difference_t<R>) -> take_view<views::all_t<R>>; } ``` #### Class template `std::ranges::take_view::sentinel` ``` namespace std::ranges { template<view V> template<bool Const> class take_view<V>::sentinel { private: using Base = /*maybe-const*/<Const, V>; // exposition only template<bool OtherConst> using CI = counted_iterator<iterator_t</*maybe-const*/<OtherConst, V>>>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only public: sentinel() = default; constexpr explicit sentinel(sentinel_t<Base> end); constexpr sentinel(sentinel<!Const> s) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; constexpr sentinel_t<Base> base() const; friend constexpr bool operator==(const CI<Const>& y, const sentinel& x); template<bool OtherConst = !Const> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const CI<OtherConst>& y, const sentinel& x); }; } ``` #### Class template `[std::ranges::take\_while\_view](../ranges/take_while_view "cpp/ranges/take while view")` ``` namespace std::ranges { template<view V, class Pred> requires input_range<V> && is_object_v<Pred> && indirect_unary_predicate<const Pred, iterator_t<V>> class take_while_view : public view_interface<take_while_view<V, Pred>> { // class template take_while_view::sentinel template<bool> class sentinel; // exposition only V base_ = V(); // exposition only /*copyable-box*/<Pred> pred_; // exposition only public: take_while_view() requires default_initializable<V> && default_initializable<Pred> = default; constexpr take_while_view(V base, Pred pred); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr const Pred& pred() const; constexpr auto begin() requires (!/*simple-view*/<V>) { return ranges::begin(base_); } constexpr auto begin() const requires range<const V> && indirect_unary_predicate<const Pred, iterator_t<const V>> { return ranges::begin(base_); } constexpr auto end() requires (!/*simple-view*/<V>) { return sentinel<false>(ranges::end(base_), addressof(*pred_)); } constexpr auto end() const requires range<const V> && indirect_unary_predicate<const Pred, iterator_t<const V>> { return sentinel<true>(ranges::end(base_), addressof(*pred_)); } }; template<class R, class Pred> take_while_view(R&&, Pred) -> take_while_view<views::all_t<R>, Pred>; } ``` #### Class template `std::ranges::take_while_view::sentinel` ``` namespace std::ranges { template<view V, class Pred> requires input_range<V> && is_object_v<Pred> && indirect_unary_predicate<const Pred, iterator_t<V>> template<bool Const> class take_while_view<V, Pred>::sentinel { using Base = /*maybe-const*/<Const, V>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only const Pred* pred_ = nullptr; // exposition only public: sentinel() = default; constexpr explicit sentinel(sentinel_t<Base> end, const Pred* pred); constexpr sentinel(sentinel<!Const> s) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; constexpr sentinel_t<Base> base() const { return end_; } friend constexpr bool operator==(const iterator_t<Base>& x, const sentinel& y); template<bool OtherConst = !Const> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const iterator_t</*maybe-const*/<OtherConst, V>>& x, const sentinel& y); }; } ``` #### Class template `[std::ranges::drop\_view](../ranges/drop_view "cpp/ranges/drop view")` ``` namespace std::ranges { template<view V> class drop_view : public view_interface<drop_view<V>> { public: drop_view() requires default_initializable<V> = default; constexpr drop_view(V base, range_difference_t<V> count); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() requires (!(/*simple-view*/<V> && random_access_range<const V> && sized_range<const V>)); constexpr auto begin() const requires random_access_range<const V> && sized_range<const V>; constexpr auto end() requires (!/*simple-view*/<V>) { return ranges::end(base_); } constexpr auto end() const requires range<const V> { return ranges::end(base_); } constexpr auto size() requires sized_range<V> { const auto s = ranges::size(base_); const auto c = static_cast<decltype(s)>(count_); return s < c ? 0 : s - c; } constexpr auto size() const requires sized_range<const V> { const auto s = ranges::size(base_); const auto c = static_cast<decltype(s)>(count_); return s < c ? 0 : s - c; } private: V base_ = V(); // exposition only range_difference_t<V> count_ = 0; // exposition only }; template<class R> drop_view(R&&, range_difference_t<R>) -> drop_view<views::all_t<R>>; } ``` #### Class template `[std::ranges::drop\_while\_view](../ranges/drop_while_view "cpp/ranges/drop while view")` ``` namespace std::ranges { template<view V, class Pred> requires input_range<V> && is_object_v<Pred> && indirect_unary_predicate<const Pred, iterator_t<V>> class drop_while_view : public view_interface<drop_while_view<V, Pred>> { public: drop_while_view() requires default_initializable<V> && default_initializable<Pred> = default; constexpr drop_while_view(V base, Pred pred); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr const Pred& pred() const; constexpr auto begin(); constexpr auto end() { return ranges::end(base_); } private: V base_ = V(); // exposition only /*copyable-box*/<Pred> pred_; // exposition only }; template<class R, class Pred> drop_while_view(R&&, Pred) -> drop_while_view<views::all_t<R>, Pred>; } ``` #### Class template `std::ranges::join_view` ``` namespace std::ranges { template<input_range V> requires view<V> && input_range<range_reference_t<V>> class join_view : public view_interface<join_view<V>> { private: using InnerRng = range_reference_t<V>; // exposition only // class template join_view::iterator template<bool Const> struct iterator; // exposition only // class template join_view::sentinel template<bool Const> struct sentinel; // exposition only V base_ = V(); // exposition only /*non-propagating-cache*/<remove_cv_t<InnerRng>>inner_; // exposition only, present only when !is_reference_v<InnerRng> public: join_view() requires default_initializable<V> = default; constexpr explicit join_view(V base); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() { constexpr bool use_const = /*simple-view*/<V> && is_reference_v<range_reference_t<V>>; return iterator<use_const>{*this, ranges::begin(base_)}; } constexpr auto begin() const requires input_range<const V> && is_reference_v<range_reference_t<const V>> { return iterator<true>{*this, ranges::begin(base_)}; } constexpr auto end() { if constexpr (forward_range<V> && is_reference_v<InnerRng> && forward_range<InnerRng> && common_range<V> && common_range<InnerRng>) return iterator</*simple-view*/<V>>{*this, ranges::end(base_)}; else return sentinel</*simple-view*/<V>>{*this}; } constexpr auto end() const requires input_range<const V> && is_reference_v<range_reference_t<const V>> { if constexpr (forward_range<const V> && forward_range<range_reference_t<const V>> && common_range<const V> && common_range<range_reference_t<const V>>) return iterator<true>{*this, ranges::end(base_)}; else return sentinel<true>{*this}; } }; template<class R> explicit join_view(R&&) -> join_view<views::all_t<R>>; } ``` #### Class template `std::ranges::join_view::iterator` ``` namespace std::ranges { template<input_range V> requires view<V> && input_range<range_reference_t<V>> template<bool Const> struct join_view<V>::iterator { private: using Parent = /*maybe-const*/<Const, join_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only using OuterIter = iterator_t<Base>; // exposition only using InnerIter = iterator_t<range_reference_t<Base>>; // exposition only static constexpr bool /*ref-is-glvalue*/ = // exposition only is_reference_v<range_reference_t<Base>>; OuterIter outer_ = OuterIter(); // exposition only InnerIter inner_ = InnerIter(); // exposition only Parent* parent_ = nullptr; // exposition only constexpr void satisfy(); // exposition only public: using iterator_concept = /* see description */; using iterator_category = /* see description */; // not always present using value_type = range_value_t<range_reference_t<Base>>; using difference_type = /* see description */; iterator() requires default_initializable<OuterIter> && default_initializable<InnerIter> = default; constexpr iterator(Parent& parent, OuterIter outer); constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, OuterIter> && convertible_to<iterator_t<InnerRng>, InnerIter>; constexpr decltype(auto) operator*() const { return *inner_; } constexpr InnerIter operator->() const requires /*has-arrow*/<InnerIter> && copyable<InnerIter>; constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires /*ref-is-glvalue*/ && forward_range<Base> && forward_range<range_reference_t<Base>>; constexpr iterator& operator--() requires /*ref-is-glvalue*/ && bidirectional_range<Base> && bidirectional_range<range_reference_t<Base>> && common_range<range_reference_t<Base>>; constexpr iterator operator--(int) requires /*ref-is-glvalue*/ && bidirectional_range<Base> && bidirectional_range<range_reference_t<Base>> && common_range<range_reference_t<Base>>; friend constexpr bool operator==(const iterator& x, const iterator& y) requires /*ref-is-glvalue*/ && equality_comparable<iterator_t<Base>> && equality_comparable<iterator_t<range_reference_t<Base>>>; friend constexpr decltype(auto) iter_move(const iterator& i) noexcept(noexcept(ranges::iter_move(i.inner_))) { return ranges::iter_move(i.inner_); } friend constexpr void iter_swap(const iterator& x, const iterator& y) noexcept(noexcept(ranges::iter_swap(x.inner_, y.inner_))) requires indirectly_swappable<InnerIter>; }; } ``` #### Class template `std::ranges::join_view::sentinel` ``` namespace std::ranges { template<input_range V> requires view<V> && input_range<range_reference_t<V>> template<bool Const> struct join_view<V>::sentinel { private: using Parent = /*maybe-const*/<Const, join_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only public: sentinel() = default; constexpr explicit sentinel(Parent& parent); constexpr sentinel(sentinel<!Const> s) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; template<bool OtherConst> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); }; } ``` #### Class template `std::ranges::join_with_view` ``` namespace std::ranges { template<class R, class P> concept /*compatible-joinable-ranges*/ = // exposition only common_with<range_value_t<R>, range_value_t<P>> && common_reference_with<range_reference_t<R>, range_reference_t<P>> && common_reference_with<range_rvalue_reference_t<R>, range_rvalue_reference_t<P>>; template<class R> concept /*bidirectional-common*/ = // exposition only bidirectional_range<R> && common_range<R>; template<input_range V, forward_range Pattern> requires view<V> && input_range<range_reference_t<V>> && view<Pattern> && /*compatible-joinable-ranges*/<range_reference_t<V>, Pattern> class join_with_view : public view_interface<join_with_view<V, Pattern>> { using InnerRng = range_reference_t<V>; // exposition only V base_ = V(); // exposition only // exposition only, present only when !is_reference_v<inner-rng> /*non-propagating-cache*/<remove_cv_t<InnerRng>> inner_; Pattern pattern_ = Pattern(); // exposition only // class template join_with_view::iterator template<bool Const> struct iterator; // exposition only // class template join_with_view::sentinel template<bool Const> struct sentinel; // exposition only public: join_with_view() requires default_initializable<V> && default_initializable<Pattern> = default; constexpr join_with_view(V base, Pattern pattern); template<input_range R> requires constructible_from<V, views::all_t<R>> && constructible_from<Pattern, single_view<range_value_t<InnerRng>>> constexpr join_with_view(R&& r, range_value_t<InnerRng> e); constexpr V base() const & requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() { constexpr bool use_const = /*simple-view*/<V> && is_reference_v<InnerRng> && /*simple-view*/<Pattern>; return iterator<use_const>{*this, ranges::begin(base_)}; } constexpr auto begin() const requires input_range<const V> && forward_range<const Pattern> && is_reference_v<range_reference_t<const V>> { return iterator<true>{*this, ranges::begin(base_)}; } constexpr auto end() { if constexpr (forward_range<V> && is_reference_v<InnerRng> && forward_range<InnerRng> && common_range<V> && common_range<InnerRng>) return iterator</*simple-view*/<V> && /*simple-view*/<Pattern>>{ *this, ranges::end(base_) }; else return sentinel</*simple-view*/<V> && /*simple-view*/<Pattern>>{*this}; } constexpr auto end() const requires input_range<const V> && forward_range<const Pattern> && is_reference_v<range_reference_t<const V>> { using InnerConstRng = range_reference_t<const V>; if constexpr (forward_range<const V> && forward_range<InnerConstRng> && common_range<const V> && common_range<InnerConstRng>) return iterator<true>{*this, ranges::end(base_)}; else return sentinel<true>{*this}; } }; template<class R, class P> join_with_view(R&&, P&&) -> join_with_view<views::all_t<R>, views::all_t<P>>; template<input_range R> join_with_view(R&&, range_value_t<range_reference_t<R>>) -> join_with_view<views::all_t<R>, single_view<range_value_t<range_reference_t<R>>>>; } ``` #### Class template `std::ranges::join_with_view::iterator` ``` namespace std::ranges { template<input_range V, forward_range Pattern> requires view<V> && input_range<range_reference_t<V>> && view<Pattern> && /*compatible-joinable-ranges*/<range_reference_t<V>, Pattern> template<bool Const> class join_with_view<V, Pattern>::iterator { using Parent = /*maybe-const*/<Const, join_with_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only using InnerBase = range_reference_t<Base>; // exposition only using PatternBase = /*maybe-const*/<Const, Pattern>; // exposition only using OuterIter = iterator_t<Base>; // exposition only using InnerIter = iterator_t<InnerBase>; // exposition only using PatternIter = iterator_t<PatternBase>; // exposition only static constexpr bool /*ref-is-glvalue*/ = is_reference_v<InnerBase>; // exposition only Parent* parent_ = nullptr; // exposition only OuterIter outer_it_ = OuterIter(); // exposition only variant<PatternIter, InnerIter> inner_it_; // exposition only constexpr iterator(Parent& parent, iterator_t<Base> outer); // exposition only constexpr auto&& /*update-inner*/(const OuterIter&); // exposition only constexpr auto&& /*get-inner*/(const OuterIter&); // exposition only constexpr void /*satisfy*/(); // exposition only public: using iterator_concept = /* see description */; using iterator_category = /* see description */; // not always present using value_type = /* see description */; using difference_type = /* see description */; iterator() requires default_initializable<OuterIter> = default; constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, OuterIter> && convertible_to<iterator_t<InnerRng>, InnerIter> && convertible_to<iterator_t<Pattern>, PatternIter>; constexpr decltype(auto) operator*() const; constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires /*ref-is-glvalue*/ && forward_iterator<OuterIter> && forward_iterator<InnerIter>; constexpr iterator& operator--() requires /*ref-is-glvalue*/ && bidirectional_range<Base> && /*bidirectional-common*/<InnerBase> && /*bidirectional-common*/<PatternBase>; constexpr iterator operator--(int) requires /*ref-is-glvalue*/ && bidirectional_range<Base> && /*bidirectional-common*/<InnerBase> && /*bidirectional-common*/<PatternBase>; friend constexpr bool operator==(const iterator& x, const iterator& y) requires /*ref-is-glvalue*/ && equality_comparable<OuterIter> && equality_comparable<InnerIter>; friend constexpr decltype(auto) iter_move(const iterator& x) { using rvalue_reference = common_reference_t< iter_rvalue_reference_t<InnerIter>, iter_rvalue_reference_t<PatternIter>>; return visit<rvalue_reference>(ranges::iter_move, x.inner_it_); } friend constexpr void iter_swap(const iterator& x, const iterator& y) requires indirectly_swappable<InnerIter, PatternIter> { visit(ranges::iter_swap, x.inner_it_, y.inner_it_); } }; } ``` #### Class template `std::ranges::join_with_view::sentinel` ``` namespace std::ranges { template<input_range V, forward_range Pattern> requires view<V> && input_range<range_reference_t<V>> && view<Pattern> && /*compatible-joinable-ranges*/<range_reference_t<V>, Pattern> template<bool Const> class join_with_view<V, Pattern>::sentinel { using Parent = /*maybe-const*/<Const, join_with_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only constexpr explicit sentinel(Parent& parent); // exposition only public: sentinel() = default; constexpr sentinel(sentinel<!Const> s) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; template <bool OtherConst> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); }; } ``` #### Class template `std::ranges::lazy_split_view` ``` namespace std::ranges { template<auto> struct /*require-constant*/; // exposition only template<class R> concept /*tiny-range*/ = // exposition only sized_range<R> && requires { typename /*require-constant*/<remove_reference_t<R>::size()>; } && (remove_reference_t<R>::size() <= 1); template<input_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> && (forward_range<V> || /*tiny-range*/<Pattern>) class lazy_split_view : public view_interface<lazy_split_view<V, Pattern>> { private: V base_ = V(); // exposition only Pattern pattern_ = Pattern(); // exposition only /*non-propagating-cache*/<iterator_t<V>> current_; // exposition only, present only // if !forward_range<V> // class template lazy_split_view::/*outer-iterator*/ template<bool> struct /*outer-iterator*/; // exposition only // class template lazy_split_view::/*inner-iterator*/ template<bool> struct /*inner-iterator*/; // exposition only public: lazy_split_view() requires default_initializable<V> && default_initializable<Pattern> = default; constexpr lazy_split_view(V base, Pattern pattern); template<input_range R> requires constructible_from<V, views::all_t<R>> && constructible_from<Pattern, single_view<range_value_t<R>>> constexpr lazy_split_view(R&& r, range_value_t<R> e); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() { if constexpr (forward_range<V>) { return /*outer-iterator*/</*simple-view*/<V> && /*simple-view*/<Pattern>> {*this, ranges::begin(base_)}; } else { current_ = ranges::begin(base_); return /*outer-iterator*/<false>{*this}; } } constexpr auto begin() const requires forward_range<V> && forward_range<const V> { return /*outer-iterator*/<true>{*this, ranges::begin(base_)}; } constexpr auto end() requires forward_range<V> && common_range<V> { return /*outer-iterator*/</*simple-view*/<V> && /*simple-view*/<Pattern>> {*this, ranges::end(base_)}; } constexpr auto end() const { if constexpr (forward_range<V> && forward_range<const V> && common_range<const V>) return /*outer-iterator*/<true>{*this, ranges::end(base_)}; else return default_sentinel; } }; template<class R, class P> lazy_split_view(R&&, P&&) -> lazy_split_view<views::all_t<R>, views::all_t<P>>; template<input_range R> lazy_split_view(R&&, range_value_t<R>) -> lazy_split_view<views::all_t<R>, single_view<range_value_t<R>>>; } ``` #### Class template `std::ranges::lazy_split_view::outer_iterator` ``` namespace std::ranges { template<input_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> && (forward_range<V> || /*tiny-range*/<Pattern>) template<bool Const> struct lazy_split_view<V, Pattern>::/*outer-iterator*/ { private: using Parent = /*maybe-const*/<Const, lazy_split_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only Parent* parent_ = nullptr; // exposition only iterator_t<Base> current_ = iterator_t<Base>(); // exposition only, present only // if V models forward_range bool trailing_empty_ = false; // exposition only public: using iterator_concept = conditional_t<forward_range<Base>, forward_iterator_tag, input_iterator_tag>; using iterator_category = input_iterator_tag; // present only if Base // models forward_range // class lazy_split_view::/*outer-iterator*/::value_type struct value_type; using difference_type = range_difference_t<Base>; /*outer-iterator*/() = default; constexpr explicit /*outer-iterator*/(Parent& parent) requires (!forward_range<Base>); constexpr /*outer-iterator*/(Parent& parent, iterator_t<Base> current) requires forward_range<Base>; constexpr /*outer-iterator*/(/*outer-iterator*/<!Const> i) requires Const && convertible_to<iterator_t<V>, iterator_t<Base>>; constexpr value_type operator*() const; constexpr /*outer-iterator*/& operator++(); constexpr decltype(auto) operator++(int) { if constexpr (forward_range<Base>) { auto tmp = *this; ++*this; return tmp; } else ++*this; } friend constexpr bool operator==(const /*outer-iterator*/& x, const /*outer-iterator*/& y) requires forward_range<Base>; friend constexpr bool operator==(const /*outer-iterator*/& x, default_sentinel_t); }; } ``` #### Class template `std::ranges::lazy_split_view::outer_iterator::value_type` ``` namespace std::ranges { template<input_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> && (forward_range<V> || /*tiny-range*/<Pattern>) template<bool Const> struct lazy_split_view<V, Pattern>::/*outer-iterator*/<Const>::value_type : view_interface<value_type> { private: /*outer-iterator*/ i_ = /*outer-iterator*/(); // exposition only public: value_type() = default; constexpr explicit value_type(/*outer-iterator*/ i); constexpr /*inner-iterator*/<Const> begin() const; constexpr default_sentinel_t end() const noexcept; }; } ``` #### Class template `std::ranges::lazy_split_view::inner_iterator` ``` namespace std::ranges { template<input_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> && (forward_range<V> || /*tiny-range*/<Pattern>) template<bool Const> struct lazy_split_view<V, Pattern>::/*inner-iterator*/ { private: using Base = /*maybe-const*/<Const, V>; // exposition only /*outer-iterator*/<Const> i_ = /*outer-iterator*/<Const>(); // exposition only bool incremented_ = false; // exposition only public: using iterator_concept = typename /*outer-iterator*/<Const>::iterator_concept; using iterator_category = /* see description */; // present only if Base // models forward_range using value_type = range_value_t<Base>; using difference_type = range_difference_t<Base>; /*inner-iterator*/() = default; constexpr explicit /*inner-iterator*/(/*outer-iterator*/<Const> i); constexpr const iterator_t<Base>& base() const & noexcept; constexpr iterator_t<Base> base() && requires forward_range<V>; constexpr decltype(auto) operator*() const { return *i_.current; } constexpr /*inner-iterator*/& operator++(); constexpr decltype(auto) operator++(int) { if constexpr (forward_range<Base>) { auto tmp = *this; ++*this; return tmp; } else ++*this; } friend constexpr bool operator==(const /*inner-iterator*/& x, const /*inner-iterator*/& y) requires forward_range<Base>; friend constexpr bool operator==(const /*inner-iterator*/& x, default_sentinel_t); friend constexpr decltype(auto) iter_move(const /*inner-iterator*/& i) noexcept(noexcept(ranges::iter_move(i.i_.current))) { return ranges::iter_move(i.i_.current); } friend constexpr void iter_swap(const /*inner-iterator*/& x, const /*inner-iterator*/& y) noexcept(noexcept(ranges::iter_swap(x.i_.current, y.i_.current))) requires indirectly_swappable<iterator_t<Base>>; }; } ``` #### Class template `std::ranges::split_view` ``` namespace std::ranges { template<forward_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> class split_view : public view_interface<split_view<V, Pattern>> { private: V base_ = V(); // exposition only Pattern pattern_ = Pattern(); // exposition only // class split_view::iterator struct iterator; // exposition only // class split_view::sentinel struct sentinel; // exposition only public: split_view() requires default_initializable<V> && default_initializable<Pattern> = default; constexpr split_view(V base, Pattern pattern); template<forward_range R> requires constructible_from<V, views::all_t<R>> && constructible_from<Pattern, single_view<range_value_t<R>>> constexpr split_view(R&& r, range_value_t<R> e); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr iterator begin(); constexpr auto end() { if constexpr (common_range<V>) { return iterator{*this, ranges::end(base_), {} }; } else { return sentinel{*this}; } } constexpr subrange<iterator_t<V>> /*find-next*/(iterator_t<V>); // exposition only }; template<class R, class P> split_view(R&&, P&&) -> split_view<views::all_t<R>, views::all_t<P>>; template<forward_range R> split_view(R&&, range_value_t<R>) -> split_view<views::all_t<R>, single_view<range_value_t<R>>>; } ``` #### Class template `std::ranges::split_view::iterator` ``` namespace std::ranges { template<forward_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> class split_view<V, Pattern>::iterator { private: split_view* parent_ = nullptr; // exposition only iterator_t<V> cur_ = iterator_t<V>(); // exposition only subrange<iterator_t<V>> next_ = subrange<iterator_t<V>>(); // exposition only bool trailing_empty_ = false; // exposition only public: using iterator_concept = forward_iterator_tag; using iterator_category = input_iterator_tag; using value_type = subrange<iterator_t<V>>; using difference_type = range_difference_t<V>; iterator() = default; constexpr iterator(split_view& parent, iterator_t<V> current, subrange<iterator_t<V>> next); constexpr iterator_t<V> base() const; constexpr value_type operator*() const; constexpr iterator& operator++(); constexpr iterator operator++(int); friend constexpr bool operator==(const iterator& x, const iterator& y); }; } ``` #### Class template `std::ranges::split_view::sentinel` ``` namespace std::ranges { template<forward_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, ranges::equal_to> struct split_view<V, Pattern>::sentinel { private: sentinel_t<V> end_ = sentinel_t<V>(); // exposition only public: sentinel() = default; constexpr explicit sentinel(split_view& parent); friend constexpr bool operator==(const iterator& x, const sentinel& y); }; } ``` #### Class template `std::ranges::common_view` ``` namespace std::ranges { template<view V> requires (!common_range<V> && copyable<iterator_t<V>>) class common_view : public view_interface<common_view<V>> { private: V base_ = V(); // exposition only public: common_view() requires default_initializable<V> = default; constexpr explicit common_view(V r); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() { if constexpr (random_access_range<V> && sized_range<V>) return ranges::begin(base_); else return common_iterator<iterator_t<V>, sentinel_t<V>>(ranges::begin(base_)); } constexpr auto begin() const requires range<const V> { if constexpr (random_access_range<const V> && sized_range<const V>) return ranges::begin(base_); else return common_iterator<iterator_t<const V>, sentinel_t<const V>>(ranges::begin(base_)); } constexpr auto end() { if constexpr (random_access_range<V> && sized_range<V>) return ranges::begin(base_) + ranges::size(base_); else return common_iterator<iterator_t<V>, sentinel_t<V>>(ranges::end(base_)); } constexpr auto end() const requires range<const V> { if constexpr (random_access_range<const V> && sized_range<const V>) return ranges::begin(base_) + ranges::size(base_); else return common_iterator<iterator_t<const V>, sentinel_t<const V>>(ranges::end(base_)); } constexpr auto size() requires sized_range<V> { return ranges::size(base_); } constexpr auto size() const requires sized_range<const V> { return ranges::size(base_); } }; template<class R> common_view(R&&) -> common_view<views::all_t<R>>; } ``` #### Class template `[std::ranges::reverse\_view](../ranges/reverse_view "cpp/ranges/reverse view")` ``` namespace std::ranges { template<view V> requires bidirectional_range<V> class reverse_view : public view_interface<reverse_view<V>> { private: V base_ = V(); // exposition only public: reverse_view() requires default_initializable<V> = default; constexpr explicit reverse_view(V r); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr reverse_iterator<iterator_t<V>> begin(); constexpr reverse_iterator<iterator_t<V>> begin() requires common_range<V>; constexpr auto begin() const requires common_range<const V>; constexpr reverse_iterator<iterator_t<V>> end(); constexpr auto end() const requires common_range<const V>; constexpr auto size() requires sized_range<V> { return ranges::size(base_); } constexpr auto size() const requires sized_range<const V> { return ranges::size(base_); } }; template<class R> reverse_view(R&&) -> reverse_view<views::all_t<R>>; } ``` #### Class template `std::ranges::elements_view` ``` namespace std::ranges { template<class T, size_t N> concept /*has-tuple-element*/ = // exposition only requires(T t) { typename tuple_size<T>::type; requires N < tuple_size_v<T>; typename tuple_element_t<N, T>; { std::get<N>(t) } -> convertible_to<const tuple_element_t<N, T>&>; }; template<class T, size_t N> concept /*returnable-element*/ = // exposition only is_reference_v<T> || move_constructible<tuple_element_t<N, T>>; template<input_range V, size_t N> requires view<V> && /*has-tuple-element*/<range_value_t<V>, N> && /*has-tuple-element*/<remove_reference_t<range_reference_t<V>>, N> && /*returnable-element*/<range_reference_t<V>, N> class elements_view : public view_interface<elements_view<V, N>> { public: elements_view() requires default_initializable<V> = default; constexpr explicit elements_view(V base); constexpr V base() const& requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() requires (!/*simple-view*/<V>) { return iterator<false>(ranges::begin(base_)); } constexpr auto begin() const requires range<const V> { return iterator<true>(ranges::begin(base_)); } constexpr auto end() requires (!/*simple-view*/<V> && !common_range<V>) { return sentinel<false>{ranges::end(base_)}; } constexpr auto end() requires (!/*simple-view*/<V> && common_range<V>) { return iterator<false>{ranges::end(base_)}; } constexpr auto end() const requires range<const V> { return sentinel<true>{ranges::end(base_)}; } constexpr auto end() const requires common_range<const V> { return iterator<true>{ranges::end(base_)}; } constexpr auto size() requires sized_range<V> { return ranges::size(base_); } constexpr auto size() const requires sized_range<const V> { return ranges::size(base_); } private: // class template elements_view::iterator template<bool> struct iterator; // exposition only // class template elements_view::sentinel template<bool> struct sentinel; // exposition only V base_ = V(); // exposition only }; } ``` #### Class template `std::ranges::elements_view::iterator` ``` namespace std::ranges { template<input_range V, size_t N> requires view<V> && /*has-tuple-element*/<range_value_t<V>, N> && /*has-tuple-element*/<remove_reference_t<range_reference_t<V>>, N> && /*returnable-element*/<range_reference_t<V>, N> template<bool Const> class elements_view<V, N>::iterator { using Base = /*maybe-const*/<Const, V>; // exposition only iterator_t<Base> current_ = iterator_t<Base>(); // exposition only static constexpr decltype(auto) /*get-element*/(const iterator_t<Base>& i); // exposition only public: using iterator_concept = /* see description */; using iterator_category = /* see description */; // not always present using value_type = remove_cvref_t<tuple_element_t<N, range_value_t<Base>>>; using difference_type = range_difference_t<Base>; iterator() requires default_initializable<iterator_t<Base>> = default; constexpr explicit iterator(iterator_t<Base> current); constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, iterator_t<Base>>; constexpr const iterator_t<Base>& base() const & noexcept; constexpr iterator_t<Base> base() &&; constexpr decltype(auto) operator*() const { return /*get-element*/(current_); } constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires forward_range<Base>; constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type x) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type x) requires random_access_range<Base>; constexpr decltype(auto) operator[](difference_type n) const requires random_access_range<Base> { return /*get-element*/(current_ + n); } friend constexpr bool operator==(const iterator& x, const iterator& y) requires equality_comparable<iterator_t<Base>>; friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable<iterator_t<Base>>; friend constexpr iterator operator+(const iterator& x, difference_type y) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type x, const iterator& y) requires random_access_range<Base>; friend constexpr iterator operator-(const iterator& x, difference_type y) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for<iterator_t<Base>, iterator_t<Base>>; }; } ``` #### Class template `std::ranges::elements_view::sentinel` ``` namespace std::ranges { template<input_range V, size_t N> requires view<V> && /*has-tuple-element*/<range_value_t<V>, N> && /*has-tuple-element*/<remove_reference_t<range_reference_t<V>>, N> && /*returnable-element*/<range_reference_t<V>, N> template<bool Const> class elements_view<V, N>::sentinel { private: using Base = /*maybe-const*/<Const, V>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only public: sentinel() = default; constexpr explicit sentinel(sentinel_t<Base> end); constexpr sentinel(sentinel<!Const> other) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; constexpr sentinel_t<Base> base() const; template<bool OtherConst> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, V>> operator-(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, V>> operator-(const sentinel& x, const iterator<OtherConst>& y); }; } ``` #### Class template `std::ranges::zip_view` ``` namespace std::ranges { template<class... Rs> concept /*zip-is-common*/ = // exposition only (sizeof...(Rs) == 1 && (common_range<Rs> && ...)) || (!(bidirectional_range<Rs> && ...) && (common_range<Rs> && ...)) || ((random_access_range<Rs> && ...) && (sized_range<Rs> && ...)); template<class... Ts> using /*tuple-or-pair*/ = /* see description */; // exposition only template<class F, class Tuple> constexpr auto /*tuple-transform*/(F&& f, Tuple&& tuple) { // exposition only return apply([&]<class... Ts>(Ts&&... elements) { return /*tuple-or-pair*/<invoke_result_t<F&, Ts>...>( invoke(f, std::forward<Ts>(elements))... ); }, std::forward<Tuple>(tuple)); } template<class F, class Tuple> constexpr void /*tuple-for-each*/(F&& f, Tuple&& tuple) { // exposition only apply([&]<class... Ts>(Ts&&... elements) { (invoke(f, std::forward<Ts>(elements)), ...); }, std::forward<Tuple>(tuple)); } template<input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) class zip_view : public view_interface<zip_view<Views...>> { tuple<Views...> views_; // exposition only // class template zip_view::iterator template<bool> class iterator; // exposition only // class template zip_view::sentinel template<bool> class sentinel; // exposition only public: zip_view() = default; constexpr explicit zip_view(Views... views); constexpr auto begin() requires (!(/*simple-view*/<Views> && ...)) { return iterator<false>(/*tuple-transform*/(ranges::begin, views_)); } constexpr auto begin() const requires (range<const Views> && ...) { return iterator<true>(/*tuple-transform*/(ranges::begin, views_)); } constexpr auto end() requires (!(/*simple-view*/<Views> && ...)) { if constexpr (!/*zip-is-common*/<Views...>) { return sentinel<false>(/*tuple-transform*/(ranges::end, views_)); } else if constexpr ((random_access_range<Views> && ...)) { return begin() + iter_difference_t<iterator<false>>(size()); } else { return iterator<false>(/*tuple-transform*/(ranges::end, views_)); } } constexpr auto end() const requires (range<const Views> && ...) { if constexpr (!/*zip-is-common*/<const Views...>) { return sentinel<true>(/*tuple-transform*/(ranges::end, views_)); } else if constexpr ((random_access_range<const Views> && ...)) { return begin() + iter_difference_t<iterator<true>>(size()); } else { return iterator<true>(/*tuple-transform*/(ranges::end, views_)); } } constexpr auto size() requires (sized_range<Views> && ...); constexpr auto size() const requires (sized_range<const Views> && ...); }; template<class... Rs> zip_view(Rs&&...) -> zip_view<views::all_t<Rs>...>; } ``` #### Class template `std::ranges::zip_view::iterator` ``` namespace std::ranges { template<bool Const, class... Views> concept /*all-random-access*/ = // exposition only (random_access_range</*maybe-const*/<Const, Views>> && ...); template<bool Const, class... Views> concept /*all-bidirectional*/ = // exposition only (bidirectional_range</*maybe-const*/<Const, Views>> && ...); template<bool Const, class... Views> concept /*all-forward*/ = // exposition only (forward_range</*maybe-const*/<Const, Views>> && ...); template<input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) template<bool Const> class zip_view<Views...>::iterator { /*tuple-or-pair*/<iterator_t</*maybe-const*/<Const, Views>>...> current_; // exposition only constexpr explicit iterator(/*tuple-or-pair*/<iterator_t< /*maybe-const*/<Const, Views>>...>); // exposition only public: using iterator_category = input_iterator_tag; // not always present using iterator_concept = /* see description */; using value_type = /*tuple-or-pair*/<range_value_t< /*maybe-const*/<Const, Views>>...>; using difference_type = common_type_t<range_difference_t< /*maybe-const*/<Const, Views>>...>; iterator() = default; constexpr iterator(iterator<!Const> i) requires Const && (convertible_to<iterator_t<Views>, iterator_t</*maybe-const*/<Const, Views>>> && ...); constexpr auto operator*() const; constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires /*all-forward*/<Const, Views...>; constexpr iterator& operator--() requires /*all-bidirectional*/<Const, Views...>; constexpr iterator operator--(int) requires /*all-bidirectional*/<Const, Views...>; constexpr iterator& operator+=(difference_type x) requires /*all-random-access*/<Const, Views...>; constexpr iterator& operator-=(difference_type x) requires /*all-random-access*/<Const, Views...>; constexpr auto operator[](difference_type n) const requires /*all-random-access*/<Const, Views...>; friend constexpr bool operator==(const iterator& x, const iterator& y) requires (equality_comparable<iterator_t</*maybe-const*/<Const, Views>>> && ...); friend constexpr bool operator<(const iterator& x, const iterator& y) requires /*all-random-access*/<Const, Views...>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires /*all-random-access*/<Const, Views...>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires /*all-random-access*/<Const, Views...>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires /*all-random-access*/<Const, Views...>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires /*all-random-access*/<Const, Views...> && (three_way_comparable<iterator_t</*maybe-const*/<Const, Views>>> && ...); friend constexpr iterator operator+(const iterator& i, difference_type n) requires /*all-random-access*/<Const, Views...>; friend constexpr iterator operator+(difference_type n, const iterator& i) requires /*all-random-access*/<Const, Views...>; friend constexpr iterator operator-(const iterator& i, difference_type n) requires /*all-random-access*/<Const, Views...>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires (sized_sentinel_for<iterator_t</*maybe-const*/<Const, Views>>, iterator_t</*maybe-const*/<Const, Views>>> && ...); friend constexpr auto iter_move(const iterator& i) noexcept(/* see description */); friend constexpr void iter_swap(const iterator& l, const iterator& r) noexcept(/* see description */) requires (indirectly_swappable<iterator_t</*maybe-const*/<Const, Views>>> && ...); }; } ``` #### Class template `std::ranges::zip_view::sentinel` ``` namespace std::ranges { template<input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) template<bool Const> class zip_view<Views...>::sentinel { /*tuple-or-pair*/<sentinel_t</*maybe-const*/<Const, Views>>...> end_; // exposition only constexpr explicit sentinel(/*tuple-or-pair*/<sentinel_t< /*maybe-const*/<Const, Views>>...> end); // exposition only public: sentinel() = default; constexpr sentinel(sentinel<!Const> i) requires Const && (convertible_to<sentinel_t<Views>, sentinel_t< /*maybe-const*/<Const, Views>>> && ...); template<bool OtherConst> requires (sentinel_for<sentinel_t</*maybe-const*/<Const, Views>>, iterator_t</*maybe-const*/<OtherConst, Views>>> && ...) friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires (sized_sentinel_for<sentinel_t</*maybe-const*/<Const, Views>>, iterator_t</*maybe-const*/<OtherConst, Views>>> && ...) friend constexpr common_type_t<range_difference_t< /*maybe-const*/<OtherConst, Views>>...> operator-(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires (sized_sentinel_for<sentinel_t</*maybe-const*/<Const, Views>>, iterator_t</*maybe-const*/<OtherConst, Views>>> && ...) friend constexpr common_type_t<range_difference_t< /*maybe-const*/<OtherConst, Views>>...> operator-(const sentinel& y, const iterator<OtherConst>& x); }; } ``` #### Class template `std::ranges::zip_transform_view` ``` namespace std::ranges { template<copy_constructible F, input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) && is_object_v<F> && regular_invocable<F&, range_reference_t<Views>...> && /*can-reference*/<invoke_result_t<F&, range_reference_t<Views>...>> class zip_transform_view : public view_interface<zip_transform_view<F, Views...>> { /*copyable-box*/<F> fun_; // exposition only zip_view<Views...> zip_; // exposition only using InnerView = zip_view<Views...>; // exposition only template<bool Const> using ziperator = iterator_t</*maybe-const*/<Const, InnerView>>; // exposition only template<bool Const> using zentinel = sentinel_t</*maybe-const*/<Const, InnerView>>; // exposition only // class template zip_transform_view::iterator template<bool> class iterator; // exposition only // class template zip_transform_view::sentinel template<bool> class sentinel; // exposition only public: zip_transform_view() = default; constexpr explicit zip_transform_view(F fun, Views... views); constexpr auto begin() { return iterator<false>(*this, zip_.begin()); } constexpr auto begin() const requires range<const InnerView> && regular_invocable<const F&, range_reference_t<const Views>...> { return iterator<true>(*this, zip_.begin()); } constexpr auto end() { if constexpr (common_range<InnerView>) { return iterator<false>(*this, zip_.end()); } else { return sentinel<false>(zip_.end()); } } constexpr auto end() const requires range<const InnerView> && regular_invocable<const F&, range_reference_t<const Views>...> { if constexpr (common_range<const InnerView>) { return iterator<true>(*this, zip_.end()); } else { return sentinel<true>(zip_.end()); } } constexpr auto size() requires sized_range<InnerView> { return zip_.size(); } constexpr auto size() const requires sized_range<const InnerView> { return zip_.size(); } }; template<class F, class... Rs> zip_transform_view(F, Rs&&...) -> zip_transform_view<F, views::all_t<Rs>...>; } ``` #### Class template `std::ranges::zip_transform_view::iterator` ``` namespace std::ranges { template<copy_constructible F, input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) && is_object_v<F> && regular_invocable<F&, range_reference_t<Views>...> && /*can-reference*/<invoke_result_t<F&, range_reference_t<Views>...>> template<bool Const> class zip_transform_view<F, Views...>::iterator { using Parent = /*maybe-const*/<Const, zip_transform_view>; // exposition only using Base = /*maybe-const*/<Const, InnerView>; // exposition only Parent* parent_ = nullptr; // exposition only ziperator<Const> inner_; // exposition only constexpr iterator(Parent& parent, ziperator<Const> inner); // exposition only public: using iterator_category = /* see description */; // not always present using iterator_concept = typename ziperator<Const>::iterator_concept; using value_type = remove_cvref_t<invoke_result_t</*maybe-const*/<Const, F>&, range_reference_t< /*maybe-const*/<Const, Views>>...>>; using difference_type = range_difference_t<Base>; iterator() = default; constexpr iterator(iterator<!Const> i) requires Const && convertible_to<ziperator<false>, ziperator<Const>>; constexpr decltype(auto) operator*() const noexcept(/* see description */); constexpr iterator& operator++(); constexpr void operator++(int); constexpr iterator operator++(int) requires forward_range<Base>; constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type x) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type x) requires random_access_range<Base>; constexpr decltype(auto) operator[](difference_type n) const requires random_access_range<Base>; friend constexpr bool operator==(const iterator& x, const iterator& y) requires equality_comparable<ziperator<Const>>; friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable<ziperator<Const>>; friend constexpr iterator operator+(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type n, const iterator& i) requires random_access_range<Base>; friend constexpr iterator operator-(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for<ziperator<Const>, ziperator<Const>>; }; } ``` #### Class template `std::ranges::zip_transform_view::sentinel` ``` namespace std::ranges { template<copy_constructible F, input_range... Views> requires (view<Views> && ...) && (sizeof...(Views) > 0) && is_object_v<F> && regular_invocable<F&, range_reference_t<Views>...> && /*can-reference*/<invoke_result_t<F&, range_reference_t<Views>...>> template<bool Const> class zip_transform_view<F, Views...>::sentinel { zentinel<Const> inner_; // exposition only constexpr explicit sentinel(zentinel<Const> inner); // exposition only public: sentinel() = default; constexpr sentinel(sentinel<!Const> i) requires Const && convertible_to<zentinel<false>, zentinel<Const>>; template<bool OtherConst> requires sentinel_for<zentinel<Const>, ziperator<OtherConst>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<zentinel<Const>, ziperator<OtherConst>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, InnerView>> operator-(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<zentinel<Const>, ziperator<OtherConst>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, InnerView>> operator-(const sentinel& x, const iterator<OtherConst>& y); }; } ``` #### Class template `std::ranges::adjacent_view` ``` namespace std::ranges { template<forward_range V, size_t N> requires view<V> && (N > 0) class adjacent_view : public view_interface<adjacent_view<V, N>> { V base_ = V(); // exposition only // class template adjacent_view::iterator template<bool> class iterator; // exposition only // class template adjacent_view::sentinel template<bool> class sentinel; // exposition only struct /*as-sentinel*/{}; // exposition only public: adjacent_view() requires default_initializable<V> = default; constexpr explicit adjacent_view(V base); constexpr auto begin() requires (!/*simple-view*/<V>) { return iterator<false>(ranges::begin(base_), ranges::end(base_)); } constexpr auto begin() const requires range<const V> { return iterator<true>(ranges::begin(base_), ranges::end(base_)); } constexpr auto end() requires (!/*simple-view*/<V>) { if constexpr (common_range<V>) { return iterator<false>(/*as-sentinel*/{}, ranges::begin(base_), ranges::end(base_)); } else { return sentinel<false>(ranges::end(base_)); } } constexpr auto end() const requires range<const V> { if constexpr (common_range<const V>) { return iterator<true>(/*as-sentinel*/{}, ranges::begin(base_), ranges::end(base_)); } else { return sentinel<true>(ranges::end(base_)); } } constexpr auto size() requires sized_range<V>; constexpr auto size() const requires sized_range<const V>; }; } ``` #### Class template `std::ranges::adjacent_view::iterator` ``` namespace std::ranges { template<forward_range V, size_t N> requires view<V> && (N > 0) template<bool Const> class adjacent_view<V, N>::iterator { using Base = /*maybe-const*/<Const, V>; // exposition only array<iterator_t<Base>, N> current_ = array<iterator_t<Base>, N>(); // exposition only constexpr iterator(iterator_t<Base> first, sentinel_t<Base> last); // exposition only constexpr iterator(/*as-sentinel*/, iterator_t<Base> first, iterator_t<Base> last); // exposition only public: using iterator_category = input_iterator_tag; using iterator_concept = /* see description */; using value_type = /*tuple-or-pair*/</*REPEAT*/(range_value_t<Base>, N)...>; using difference_type = range_difference_t<Base>; iterator() = default; constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, iterator_t<Base>>; constexpr auto operator*() const; constexpr iterator& operator++(); constexpr iterator operator++(int); constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type x) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type x) requires random_access_range<Base>; constexpr auto operator[](difference_type n) const requires random_access_range<Base>; friend constexpr bool operator==(const iterator& x, const iterator& y); friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable<iterator_t<Base>>; friend constexpr iterator operator+(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type n, const iterator& i) requires random_access_range<Base>; friend constexpr iterator operator-(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for<iterator_t<Base>, iterator_t<Base>>; friend constexpr auto iter_move(const iterator& i) noexcept(/* see description */); friend constexpr void iter_swap(const iterator& l, const iterator& r) noexcept(/* see description */) requires indirectly_swappable<iterator_t<Base>>; }; } ``` #### Class template `std::ranges::adjacent_view::sentinel` ``` namespace std::ranges { template<forward_range V, size_t N> requires view<V> && (N > 0) template<bool Const> class adjacent_view<V, N>::sentinel { using Base = /*maybe-const*/<Const, V>; // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only constexpr explicit sentinel(sentinel_t<Base> end); // exposition only public: sentinel() = default; constexpr sentinel(sentinel<!Const> i) requires Const && convertible_to<sentinel_t<V>, sentinel_t<Base>>; template<bool OtherConst> requires sentinel_for<sentinel_t<Base>, iterator_t</*maybe-const*/<OtherConst, V>>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<sentinel_t<Base>, iterator_t< /*maybe-const*/<OtherConst, V>>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, V>> operator-(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for<sentinel_t<Base>, iterator_t< /*maybe-const*/<OtherConst, V>>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, V>> operator-(const sentinel& y, const iterator<OtherConst>& x); }; } ``` #### Class template `std::ranges::adjacent_transform_view` ``` namespace std::ranges { template<forward_range V, copy_constructible F, size_t N> requires view<V> && (N > 0) && is_object_v<F> && regular_invocable<F&, /*REPEAT*/(range_reference_t<V>, N)...> && /*can-reference*/<invoke_result_t<F&, /*REPEAT*/(range_reference_t<V>, N)...>> class adjacent_transform_view : public view_interface<adjacent_transform_view<V, F, N>> { /*copyable-box*/<F> fun_; // exposition only adjacent_view<V, N> inner_; // exposition only using InnerView = adjacent_view<V, N>; // exposition only template<bool Const> using /*inner-iterator*/ = iterator_t</*maybe-const*/<Const, InnerView>>; // exposition only template<bool Const> using /*inner-sentinel*/ = sentinel_t</*maybe-const*/<Const, InnerView>>; // exposition only // class template adjacent_transform_view::iterator template<bool> class iterator; // exposition only // class template adjacent_transform_view::sentinel template<bool> class sentinel; // exposition only public: adjacent_transform_view() = default; constexpr explicit adjacent_transform_view(V base, F fun); constexpr auto begin() { return iterator<false>(*this, inner_.begin()); } constexpr auto begin() const requires range<const InnerView> && regular_invocable<const F&, /*REPEAT*/(range_reference_t<const V>, N)...> { return iterator<true>(*this, inner_.begin()); } constexpr auto end() { if constexpr (common_range<InnerView>) { return iterator<false>(*this, inner_.end()); } else { return sentinel<false>(inner_.end()); } } constexpr auto end() const requires range<const InnerView> && regular_invocable<const F&, /*REPEAT*/(range_reference_t<const V>, N)...> { if constexpr (common_range<const InnerView>) { return iterator<true>(*this, inner_.end()); } else { return sentinel<true>(inner_.end()); } } constexpr auto size() requires sized_range<InnerView> { return inner_.size(); } constexpr auto size() const requires sized_range<const InnerView> { return inner_.size(); } }; } ``` #### Class template `std::ranges::adjacent_transform_view::iterator` ``` namespace std::ranges { template<forward_range V, copy_constructible F, size_t N> requires view<V> && (N > 0) && is_object_v<F> && regular_invocable<F&, /*REPEAT*/(range_reference_t<V>, N)...> && /*can-reference*/<invoke_result_t<F&, /*REPEAT*/(range_reference_t<V>, N)...>> template<bool Const> class adjacent_transform_view<F, V...>::iterator { using Parent = /*maybe-const*/<Const, adjacent_transform_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only Parent* parent_ = nullptr; // exposition only /*inner-iterator*/<Const> inner_; // exposition only constexpr iterator(Parent& parent, /*inner-iterator*/<Const> inner); // exposition only public: using iterator_category = /* see description */; using iterator_concept = typename /*inner-iterator*/<Const>::iterator_concept; using value_type = remove_cvref_t<invoke_result_t</*maybe-const*/<Const, F>&, /*REPEAT*/(range_reference_t<Base>, N)...>>; using difference_type = range_difference_t<Base>; iterator() = default; constexpr iterator(iterator<!Const> i) requires Const && convertible_to</*inner-iterator*/<false>, /*inner-iterator*/<Const>>; constexpr decltype(auto) operator*() const noexcept(/* see description */); constexpr iterator& operator++(); constexpr iterator operator++(int); constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type x) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type x) requires random_access_range<Base>; constexpr decltype(auto) operator[](difference_type n) const requires random_access_range<Base>; friend constexpr bool operator==(const iterator& x, const iterator& y); friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable< /*inner-iterator*/<Const>>; friend constexpr iterator operator+(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type n, const iterator& i) requires random_access_range<Base>; friend constexpr iterator operator-(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for</*inner-iterator*/<Const>, /*inner-iterator*/<Const>>; }; } ``` #### Class template `std::ranges::adjacent_transform_view::sentinel` ``` namespace std::ranges { template<forward_range V, copy_constructible F, size_t N> requires view<V> && (N > 0) && is_object_v<F> && regular_invocable<F&, /*REPEAT*/(range_reference_t<V>, N)...> && /*can-reference*/<invoke_result_t<F&, /*REPEAT*/(range_reference_t<V>, N)...>> template<bool Const> class adjacent_transform_view<V, F, N>::sentinel { /*inner-sentinel*/<Const> inner_; // exposition only constexpr explicit sentinel(/*inner-sentinel*/<Const> inner); // exposition only public: sentinel() = default; constexpr sentinel(sentinel<!Const> i) requires Const && convertible_to</*inner-sentinel*/<false>, /*inner-sentinel*/<Const>>; template<bool OtherConst> requires sentinel_for</*inner-sentinel*/<Const>, /*inner-iterator*/<OtherConst>> friend constexpr bool operator==(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for</*inner-sentinel*/<Const>, /*inner-iterator*/<OtherConst>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, InnerView>> operator-(const iterator<OtherConst>& x, const sentinel& y); template<bool OtherConst> requires sized_sentinel_for</*inner-sentinel*/<Const>, /*inner-iterator*/<OtherConst>> friend constexpr range_difference_t</*maybe-const*/<OtherConst, InnerView>> operator-(const sentinel& x, const iterator<OtherConst>& y); }; } ``` #### Class template `std::ranges::chunk_view` for input ranges ``` namespace std::ranges { template<class I> constexpr I /*div-ceil*/(I num, I denom) { // exposition only I r = num / denom; if (num % denom) ++r; return r; } template<view V> requires input_range<V> class chunk_view : public view_interface<chunk_view<V>> { V base_ = V(); // exposition only range_difference_t<V> n_ = 0; // exposition only range_difference_t<V> remainder_ = 0; // exposition only /*non-propagating-cache*/<iterator_t<V>> current_; // exposition only // class chunk_view::/*outer-iterator*/ class /*outer-iterator*/; // exposition only // class chunk_view::/*inner-iterator*/ class /*inner-iterator*/; // exposition only public: chunk_view() requires default_initializable<V> = default; constexpr explicit chunk_view(V base, range_difference_t<V> n); constexpr V base() const & requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr /*outer-iterator*/ begin(); constexpr default_sentinel_t end() noexcept; constexpr auto size() requires sized_range<V>; constexpr auto size() const requires sized_range<const V>; }; template<class R> chunk_view(R&& r, range_difference_t<R>) -> chunk_view<views::all_t<R>>; } ``` #### Class template `std::ranges::chunk_view::outer_iterator` for input ranges ``` namespace std::ranges { template<view V> requires input_range<V> class chunk_view<V>::/*outer-iterator*/ { chunk_view* parent_; // exposition only constexpr explicit /*outer-iterator*/(chunk_view& parent); // exposition only public: using iterator_concept = input_iterator_tag; using difference_type = range_difference_t<V>; // class chunk_view::/*outer-iterator*/::value_type struct value_type; /*outer-iterator*/(/*outer-iterator*/&&) = default; /*outer-iterator*/r& operator=(/*outer-iterator*/&&) = default; constexpr value_type operator*() const; constexpr /*outer-iterator*/& operator++(); constexpr void operator++(int); friend constexpr bool operator==(const /*outer-iterator*/& x, default_sentinel_t); friend constexpr difference_type operator-(default_sentinel_t y, const /*outer-iterator*/& x) requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; friend constexpr difference_type operator-(const /*outer-iterator*/& x, default_sentinel_t y) requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; }; } ``` #### Class template `std::ranges::chunk_view::outer_iterator::value_type` for input ranges ``` namespace std::ranges { template<view V> requires input_range<V> struct chunk_view<V>::/*outer-iterator*/::value_type : view_interface<value_type> { private: chunk_view* parent_; // exposition only constexpr explicit value_type(chunk_view& parent); // exposition only public: constexpr /*inner-iterator*/ begin() const noexcept; constexpr default_sentinel_t end() const noexcept; constexpr auto size() const requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; }; } ``` #### Class template `std::ranges::chunk_view::inner_iterator` for input ranges ``` namespace std::ranges { template<view V> requires input_range<V> class chunk_view<V>::/*inner-iterator*/ { chunk_view* parent_; // exposition only constexpr explicit /*inner-iterator*/(chunk_view& parent) noexcept; // exposition only public: using iterator_concept = input_iterator_tag; using difference_type = range_difference_t<V>; using value_type = range_value_t<V>; /*inner-iterator*/(/*inner-iterator*/&&) = default; /*inner-iterator*/& operator=(/*inner-iterator*/&&) = default; constexpr const iterator_t<V>& base() const &; constexpr range_reference_t<V> operator*() const; constexpr /*inner-iterator*/& operator++(); constexpr void operator++(int); friend constexpr bool operator==(const /*inner-iterator*/& x, default_sentinel_t); friend constexpr difference_type operator-(default_sentinel_t y, const /*inner-iterator*/& x) requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; friend constexpr difference_type operator-(const /*inner-iterator*/& x, default_sentinel_t y) requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; }; } ``` #### Class template `std::ranges::chunk_view` for forward ranges ``` namespace std::ranges { template<view V> requires forward_range<V> class chunk_view<V> : public view_interface<chunk_view<V>> { V base_ = V(); // exposition only range_difference_t<V> n_ = 0; // exposition only // class template chunk_view::iterator template<bool> class iterator; // exposition only public: chunk_view() requires default_initializable<V> = default; constexpr explicit chunk_view(V base, range_difference_t<V> n); constexpr V base() const & requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr auto begin() requires (!/*simple-view*/<V>) { return iterator<false>(this, ranges::begin(base_)); } constexpr auto begin() const requires forward_range<const V> { return iterator<true>(this, ranges::begin(base_)); } constexpr auto end() requires (!/*simple-view*/<V>) { if constexpr (common_range<V> && sized_range<V>) { auto missing = (n_ - ranges::distance(base_) % n_) % n_; return iterator<false>(this, ranges::end(base_), missing); } else if constexpr (common_range<V> && !bidirectional_range<V>) { return iterator<false>(this, ranges::end(base_)); } else { return default_sentinel; } } constexpr auto end() const requires forward_range<const V> { if constexpr (common_range<const V> && sized_range<const V>) { auto missing = (n_ - ranges::distance(base_) % n_) % n_; return iterator<true>(this, ranges::end(base_), missing); } else if constexpr (common_range<const V> && !bidirectional_range<const V>) { return iterator<true>(this, ranges::end(base_)); } else { return default_sentinel; } } constexpr auto size() requires sized_range<V>; constexpr auto size() const requires sized_range<const V>; }; } ``` #### Class template `std::ranges::chunk_view::iterator` for forward ranges ``` namespace std::ranges { template<view V> requires forward_range<V> template<bool Const> class chunk_view<V>::iterator { using Parent = /*maybe-const*/<Const, chunk_view>; // exposition only using Base = /*maybe-const*/<Const, V>; // exposition only iterator_t<Base> current_ = iterator_t<Base>(); // exposition only sentinel_t<Base> end_ = sentinel_t<Base>(); // exposition only range_difference_t<Base> n_ = 0; // exposition only range_difference_t<Base> missing_ = 0; // exposition only constexpr iterator(Parent* parent, iterator_t<Base> current, // exposition only range_difference_t<Base> missing = 0); public: using iterator_category = input_iterator_tag; using iterator_concept = /* see description */; using value_type = decltype(views::take(subrange(current_, end_), n_)); using difference_type = range_difference_t<Base>; iterator() = default; constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, iterator_t<Base>> && convertible_to<sentinel_t<V>, sentinel_t<Base>>; constexpr iterator_t<Base> base() const; constexpr value_type operator*() const; constexpr iterator& operator++(); constexpr iterator operator++(int); constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type x) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type x) requires random_access_range<Base>; constexpr value_type operator[](difference_type n) const requires random_access_range<Base>; friend constexpr bool operator==(const iterator& x, const iterator& y); friend constexpr bool operator==(const iterator& x, default_sentinel_t); friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable<iterator_t<Base>>; friend constexpr iterator operator+(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type n, const iterator& i) requires random_access_range<Base>; friend constexpr iterator operator-(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for<iterator_t<Base>, iterator_t<Base>>; friend constexpr difference_type operator-(default_sentinel_t y, const iterator& x) requires sized_sentinel_for<sentinel_t<Base>, iterator_t<Base>>; friend constexpr difference_type operator-(const iterator& x, default_sentinel_t y) requires sized_sentinel_for<sentinel_t<Base>, iterator_t<Base>>; }; } ``` #### Class template `std::ranges::slide_view` ``` namespace std::ranges { template<class V> concept /*slide-caches-nothing*/ = random_access_range<V> // exposition only && sized_range<V>; template<class V> concept /*slide-caches-last*/ = // exposition only !/*slide-caches-nothing*/<V> && bidirectional_range<V> && common_range<V>; template<class V> concept /*slide-caches-first*/ = // exposition only !/*slide-caches-nothing*/<V> && !/*slide-caches-last*/<V>; template<forward_range V> requires view<V> class slide_view : public view_interface<slide_view<V>> { V base_ = V(); // exposition only range_difference_t<V> n_ = 0; // exposition only // class template slide_view::iterator template<bool> class iterator; // exposition only // class slide_view::sentinel class sentinel; // exposition only public: slide_view() requires default_initializable<V> = default; constexpr explicit slide_view(V base, range_difference_t<V> n); constexpr auto begin() requires (!(/*simple-view*/<V> && /*slide-caches-nothing*/<const V>)); constexpr auto begin() const requires /*slide-caches-nothing*/<const V>; constexpr auto end() requires (!(/*simple-view*/<V> && /*slide-caches-nothing*/<const V>)); constexpr auto end() const requires /*slide-caches-nothing*/<const V>; constexpr auto size() requires sized_range<V>; constexpr auto size() const requires sized_range<const V>; }; template<class R> slide_view(R&& r, range_difference_t<R>) -> slide_view<views::all_t<R>>; } ``` #### Class template `std::ranges::slide_view::iterator` ``` namespace std::ranges { template<forward_range V> requires view<V> template<bool Const> class slide_view<V>::iterator { using Base = /*maybe-const*/<Const, V>; // exposition only iterator_t<Base> current_ = iterator_t<Base>(); // exposition only iterator_t<Base> last_ele_ = iterator_t<Base>(); // exposition only, // present only if Base models slide-caches-first range_difference_t<Base> n_ = 0; // exposition only constexpr iterator(iterator_t<Base> current, range_difference_t<Base> n) // exposition only requires (!/*slide-caches-first*/<Base>); constexpr iterator(iterator_t<Base> current, iterator_t<Base> last_elem, range_difference_t<Base> n) // exposition only requires /*slide-caches-first*/<Base>; public: using iterator_category = input_iterator_tag; using iterator_concept = /* see description */; using value_type = decltype(views::counted(current_, n_)); using difference_type = range_difference_t<Base>; iterator() = default; constexpr iterator(iterator<!Const> i) requires Const && convertible_to<iterator_t<V>, iterator_t<Base>>; constexpr auto operator*() const; constexpr iterator& operator++(); constexpr iterator operator++(int); constexpr iterator& operator--() requires bidirectional_range<Base>; constexpr iterator operator--(int) requires bidirectional_range<Base>; constexpr iterator& operator+=(difference_type x) requires random_access_range<Base>; constexpr iterator& operator-=(difference_type x) requires random_access_range<Base>; constexpr auto operator[](difference_type n) const requires random_access_range<Base>; friend constexpr bool operator==(const iterator& x, const iterator& y); friend constexpr bool operator<(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator<=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr bool operator>=(const iterator& x, const iterator& y) requires random_access_range<Base>; friend constexpr auto operator<=>(const iterator& x, const iterator& y) requires random_access_range<Base> && three_way_comparable<iterator_t<Base>>; friend constexpr iterator operator+(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr iterator operator+(difference_type n, const iterator& i) requires random_access_range<Base>; friend constexpr iterator operator-(const iterator& i, difference_type n) requires random_access_range<Base>; friend constexpr difference_type operator-(const iterator& x, const iterator& y) requires sized_sentinel_for<iterator_t<Base>, iterator_t<Base>>; }; } ``` #### Class template `std::ranges::slide_view::sentinel` ``` namespace std::ranges { template<forward_range V> requires view<V> class slide_view<V>::sentinel { sentinel_t<V> end_ = sentinel_t<V>(); // exposition only constexpr explicit sentinel(sentinel_t<V> end); // exposition only public: sentinel() = default; friend constexpr bool operator==(const iterator<false>& x, const sentinel& y); friend constexpr range_difference_t<V> operator-(const iterator<false>& x, const sentinel& y) requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; friend constexpr range_difference_t<V> operator-(const sentinel& y, const iterator<false>& x) requires sized_sentinel_for<sentinel_t<V>, iterator_t<V>>; }; } ``` #### Class template `std::ranges::chunk_by_view` ``` namespace std::ranges { template<forward_range V, indirect_binary_predicate<iterator_t<V>, iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class chunk_by_view : public view_interface<chunk_by_view<V, Pred>> { V base_ = V(); // exposition only /*copyable-box*/<Pred> pred_ = Pred(); // exposition only // class chunk_by_view::iterator class iterator; // exposition only public: chunk_by_view() requires default_initializable<V> && default_initializable<Pred> = default; constexpr explicit chunk_by_view(V base, Pred pred); constexpr V base() const & requires copy_constructible<V> { return base_; } constexpr V base() && { return std::move(base_); } constexpr const Pred& pred() const; constexpr iterator begin(); constexpr auto end(); constexpr iterator_t<V> /*find-next*/(iterator_t<V>); // exposition only constexpr iterator_t<V> /*find-prev*/(iterator_t<V>) // exposition only requires bidirectional_range<V>; }; template<class R, class Pred> chunk_by_view(R&&, Pred) -> chunk_by_view<views::all_t<R>, Pred>; } ``` #### Class template `std::ranges::chunk_by_view::iterator` ``` namespace std::ranges { template<forward_range V, indirect_binary_predicate<iterator_t<V>, iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class chunk_by_view<V, Pred>::iterator { chunk_by_view* parent_ = nullptr; // exposition only iterator_t<V> current_ = iterator_t<V>(); // exposition only iterator_t<V> next_ = iterator_t<V>(); // exposition only constexpr iterator(chunk_by_view& parent, iterator_t<V> current, // exposition only iterator_t<V> next); public: using value_type = subrange<iterator_t<V>>; using difference_type = range_difference_t<V>; using iterator_category = input_iterator_tag; using iterator_concept = /* see description */; iterator() = default; constexpr value_type operator*() const; constexpr iterator& operator++(); constexpr iterator operator++(int); constexpr iterator& operator--() requires bidirectional_range<V>; constexpr iterator operator--(int) requires bidirectional_range<V>; friend constexpr bool operator==(const iterator& x, const iterator& y); friend constexpr bool operator==(const iterator& x, default_sentinel_t); }; } ```
programming_docs
cpp Standard library header <unordered_map> (C++11) Standard library header <unordered\_map> (C++11) ================================================ This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [unordered\_map](../container/unordered_map "cpp/container/unordered map") (C++11) | collection of key-value pairs, hashed by keys, keys are unique (class template) | | [unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap") (C++11) | collection of key-value pairs, hashed by keys (class template) | | Functions | | [operator==operator!=](../container/unordered_map/operator_cmp "cpp/container/unordered map/operator cmp") (removed in C++20) | compares the values in the unordered\_map (function template) | | [std::swap(std::unordered\_map)](../container/unordered_map/swap2 "cpp/container/unordered map/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_map)](../container/unordered_map/erase_if "cpp/container/unordered map/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | [operator==operator!=](../container/unordered_multimap/operator_cmp "cpp/container/unordered multimap/operator cmp") (removed in C++20) | compares the values in the unordered\_multimap (function template) | | [std::swap(std::unordered\_multimap)](../container/unordered_multimap/swap2 "cpp/container/unordered multimap/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_multimap)](../container/unordered_multimap/erase_if "cpp/container/unordered multimap/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template unordered_map template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<pair<const Key, T>>> class unordered_map; // class template unordered_multimap template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<pair<const Key, T>>> class unordered_multimap; template<class Key, class T, class Hash, class Pred, class Alloc> bool operator==(const unordered_map<Key, T, Hash, Pred, Alloc>& a, const unordered_map<Key, T, Hash, Pred, Alloc>& b); template<class Key, class T, class Hash, class Pred, class Alloc> bool operator==(const unordered_multimap<Key, T, Hash, Pred, Alloc>& a, const unordered_multimap<Key, T, Hash, Pred, Alloc>& b); template<class Key, class T, class Hash, class Pred, class Alloc> void swap(unordered_map<Key, T, Hash, Pred, Alloc>& x, unordered_map<Key, T, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); template<class Key, class T, class Hash, class Pred, class Alloc> void swap(unordered_multimap<Key, T, Hash, Pred, Alloc>& x, unordered_multimap<Key, T, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); template<class K, class T, class H, class P, class A, class Predicate> typename unordered_map<K, T, H, P, A>::size_type erase_if(unordered_map<K, T, H, P, A>& c, Predicate pred); template<class K, class T, class H, class P, class A, class Predicate> typename unordered_multimap<K, T, H, P, A>::size_type erase_if(unordered_multimap<K, T, H, P, A>& c, Predicate pred); namespace pmr { template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>> using unordered_map = std::unordered_map<Key, T, Hash, Pred, polymorphic_allocator<pair<const Key, T>>>; template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>> using unordered_multimap = std::unordered_multimap<Key, T, Hash, Pred, polymorphic_allocator<pair<const Key, T>>>; } } ``` #### Class template `[std::unordered\_map](../container/unordered_map "cpp/container/unordered map")` ``` namespace std { template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Allocator = allocator<pair<const Key, T>>> class unordered_map { public: // types using key_type = Key; using mapped_type = T; using value_type = pair<const Key, T>; using hasher = Hash; using key_equal = Pred; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using local_iterator = /* implementation-defined */; using const_local_iterator = /* implementation-defined */; using node_type = /* unspecified */; using insert_return_type = /*insert-return-type*/<iterator, node_type>; // construct/copy/destroy unordered_map(); explicit unordered_map(size_type n, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template<class InputIt> unordered_map(InputIt f, InputIt l, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_map(const unordered_map&); unordered_map(unordered_map&&); explicit unordered_map(const Allocator&); unordered_map(const unordered_map&, const Allocator&); unordered_map(unordered_map&&, const Allocator&); unordered_map(initializer_list<value_type> il, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_map(size_type n, const allocator_type& a) : unordered_map(n, hasher(), key_equal(), a) { } unordered_map(size_type n, const hasher& hf, const allocator_type& a) : unordered_map(n, hf, key_equal(), a) { } template<class InputIt> unordered_map(InputIt f, InputIt l, size_type n, const allocator_type& a) : unordered_map(f, l, n, hasher(), key_equal(), a) { } template<class InputIt> unordered_map(InputIt f, InputIt l, size_type n, const hasher& hf, const allocator_type& a) : unordered_map(f, l, n, hf, key_equal(), a) { } unordered_map(initializer_list<value_type> il, size_type n, const allocator_type& a) : unordered_map(il, n, hasher(), key_equal(), a) { } unordered_map(initializer_list<value_type> il, size_type n, const hasher& hf, const allocator_type& a) : unordered_map(il, n, hf, key_equal(), a) { } ~unordered_map(); unordered_map& operator=(const unordered_map&); unordered_map& operator=(unordered_map&&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Hash> && is_nothrow_move_assignable_v<Pred>); unordered_map& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> pair<iterator, bool> emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); pair<iterator, bool> insert(const value_type& obj); pair<iterator, bool> insert(value_type&& obj); template<class P> pair<iterator, bool> insert(P&& obj); iterator insert(const_iterator hint, const value_type& obj); iterator insert(const_iterator hint, value_type&& obj); template<class P> iterator insert(const_iterator hint, P&& obj); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); insert_return_type insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); template<class... Args> pair<iterator, bool> try_emplace(const key_type& k, Args&&... args); template<class... Args> pair<iterator, bool> try_emplace(key_type&& k, Args&&... args); template<class... Args> iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args); template<class... Args> iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args); template<class M> pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj); template<class M> pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj); template<class M> iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj); template<class M> iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& k); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(unordered_map&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Hash> && is_nothrow_swappable_v<Pred>); void clear() noexcept; template<class H2, class P2> void merge(unordered_map<Key, T, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_map<Key, T, H2, P2, Allocator>&& source); template<class H2, class P2> void merge(unordered_multimap<Key, T, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_multimap<Key, T, H2, P2, Allocator>&& source); // observers hasher hash_function() const; key_equal key_eq() const; // map operations iterator find(const key_type& k); const_iterator find(const key_type& k) const; template<class K> iterator find(const K& k); template<class K> const_iterator find(const K& k) const; template<class K> size_type count(const key_type& k) const; template<class K> size_type count(const K& k) const; bool contains(const key_type& k) const; template<class K> bool contains(const K& k) const; pair<iterator, iterator> equal_range(const key_type& k); pair<const_iterator, const_iterator> equal_range(const key_type& k) const; template<class K> pair<iterator, iterator> equal_range(const K& k); template<class K> pair<const_iterator, const_iterator> equal_range(const K& k) const; // element access mapped_type& operator[](const key_type& k); mapped_type& operator[](key_type&& k); mapped_type& at(const key_type& k); const mapped_type& at(const key_type& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template<class InputIt, class Hash = hash</*iter-key-type*/<InputIt>>, class Pred = equal_to</*iter-key-type*/<InputIt>>, class Allocator = allocator</*iter-to-alloc-type*/<InputIt>>> unordered_map(InputIt, InputIt, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_map</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, Hash, Pred, Allocator>; template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Allocator = allocator<pair<const Key, T>>> unordered_map(initializer_list<pair<Key, T>>, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_map<Key, T, Hash, Pred, Allocator>; template<class InputIt, class Allocator> unordered_map(InputIt, InputIt, typename /* see description */::size_type, Allocator) -> unordered_map</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, hash</*iter-key-type*/<InputIt>>, equal_to</*iter-key-type*/<InputIt>>, Allocator>; template<class InputIt, class Allocator> unordered_map(InputIt, InputIt, Allocator) -> unordered_map</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIte>, hash</*iter-key-type*/<InputIt>>, equal_to</*iter-key-type*/<InputIt>>, Allocator>; template<class InputIt, class Hash, class Allocator> unordered_map(InputIt, InputIt, typename /* see description */::size_type, Hash, Allocator) -> unordered_map</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, Hash, equal_to</*iter-key-type*/<InputIt>>, Allocator>; template<class Key, class T, class Allocator> unordered_map(initializer_list<pair<Key, T>>, typename /* see description */::size_type, Allocator) -> unordered_map<Key, T, hash<Key>, equal_to<Key>, Allocator>; template<class Key, class T, class Allocator> unordered_map(initializer_list<pair<Key, T>>, Allocator) -> unordered_map<Key, T, hash<Key>, equal_to<Key>, Allocator>; template<class Key, class T, class Hash, class Allocator> unordered_map(initializer_list<pair<Key, T>>, typename /* see description */::size_type, Hash, Allocator) -> unordered_map<Key, T, Hash, equal_to<Key>, Allocator>; // swap template<class Key, class T, class Hash, class Pred, class Alloc> void swap(unordered_map<Key, T, Hash, Pred, Alloc>& x, unordered_map<Key, T, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); } ``` #### Class template `[std::unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap")` ``` namespace std { template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Allocator = allocator<pair<const Key, T>>> class unordered_multimap { public: // types using key_type = Key; using mapped_type = T; using value_type = pair<const Key, T>; using hasher = Hash; using key_equal = Pred; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using local_iterator = /* implementation-defined */; using const_local_iterator = /* implementation-defined */; using node_type = /* unspecified */; // construct/copy/destroy unordered_multimap(); explicit unordered_multimap(size_type n, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template<class InputIt> unordered_multimap(InputIt f, InputIt l, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_multimap(const unordered_multimap&); unordered_multimap(unordered_multimap&&); explicit unordered_multimap(const Allocator&); unordered_multimap(const unordered_multimap&, const Allocator&); unordered_multimap(unordered_multimap&&, const Allocator&); unordered_multimap(initializer_list<value_type> il, size_type n = /* see description */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_multimap(size_type n, const allocator_type& a) : unordered_multimap(n, hasher(), key_equal(), a) { } unordered_multimap(size_type n, const hasher& hf, const allocator_type& a) : unordered_multimap(n, hf, key_equal(), a) { } template<class InputIt> unordered_multimap(InputIt f, InputIt l, size_type n, const allocator_type& a) : unordered_multimap(f, l, n, hasher(), key_equal(), a) { } template<class InputIt> unordered_multimap(InputIt f, InputIt l, size_type n, const hasher& hf, const allocator_type& a) : unordered_multimap(f, l, n, hf, key_equal(), a) { } unordered_multimap(initializer_list<value_type> il, size_type n, const allocator_type& a) : unordered_multimap(il, n, hasher(), key_equal(), a) { } unordered_multimap(initializer_list<value_type> il, size_type n, const hasher& hf, const allocator_type& a) : unordered_multimap(il, n, hf, key_equal(), a) { } ~unordered_multimap(); unordered_multimap& operator=(const unordered_multimap&); unordered_multimap& operator=(unordered_multimap&&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_move_assignable_v<Hash> && is_nothrow_move_assignable_v<Pred>); unordered_multimap& operator=(initializer_list<value_type>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // modifiers template<class... Args> iterator emplace(Args&&... args); template<class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& obj); iterator insert(value_type&& obj); template<class P> iterator insert(P&& obj); iterator insert(const_iterator hint, const value_type& obj); iterator insert(const_iterator hint, value_type&& obj); template<class P> iterator insert(const_iterator hint, P&& obj); template<class InputIt> void insert(InputIt first, InputIt last); void insert(initializer_list<value_type>); node_type extract(const_iterator position); node_type extract(const key_type& x); template<class K> node_type extract(K&& x); iterator insert(node_type&& nh); iterator insert(const_iterator hint, node_type&& nh); iterator erase(iterator position); iterator erase(const_iterator position); size_type erase(const key_type& k); template<class K> size_type erase(K&& x); iterator erase(const_iterator first, const_iterator last); void swap(unordered_multimap&) noexcept(allocator_traits<Allocator>::is_always_equal::value && is_nothrow_swappable_v<Hash> && is_nothrow_swappable_v<Pred>); void clear() noexcept; template<class H2, class P2> void merge(unordered_multimap<Key, T, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_multimap<Key, T, H2, P2, Allocator>&& source); template<class H2, class P2> void merge(unordered_map<Key, T, H2, P2, Allocator>& source); template<class H2, class P2> void merge(unordered_map<Key, T, H2, P2, Allocator>&& source); // observers hasher hash_function() const; key_equal key_eq() const; // map operations iterator find(const key_type& k); const_iterator find(const key_type& k) const; template<class K> iterator find(const K& k); template<class K> const_iterator find(const K& k) const; size_type count(const key_type& k) const; template<class K> size_type count(const K& k) const; bool contains(const key_type& k) const; template<class K> bool contains(const K& k) const; pair<iterator, iterator> equal_range(const key_type& k); pair<const_iterator, const_iterator> equal_range(const key_type& k) const; template<class K> pair<iterator, iterator> equal_range(const K& k); template<class K> pair<const_iterator, const_iterator> equal_range(const K& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template<class InputIt, class Hash = hash</*iter-key-type*/<InputIt>>, class Pred = equal_to</*iter-key-type*/<InputIt>>, class Allocator = allocator</*iter-to-alloc-type*/<InputIt>>> unordered_multimap(InputIt, InputIt, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_multimap<iter-key-type<InputIt>, iter-mapped-type<InputIt>, Hash, Pred, Allocator>; template<class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Allocator = allocator<pair<const Key, T>>> unordered_multimap(initializer_list<pair<Key, T>>, typename /* see description */::size_type = /* see description */, Hash = Hash(), Pred = Pred(), Allocator = Allocator()) -> unordered_multimap<Key, T, Hash, Pred, Allocator>; template<class InputIt, class Allocator> unordered_multimap(InputIt, InputIt, typename /* see description */::size_type, Allocator) -> unordered_multimap</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, hash</*iter-key-type*/<InputIt>>, equal_to</*iter-key-type*/<InputIt>>, Allocator>; template<class InputIt, class Allocator> unordered_multimap(InputIt, InputIt, Allocator) -> unordered_multimap</*iter-key-type*/<InputIt>, /*iter-mapped-type*/<InputIt>, hash</*iter-key-type*/<InputIt>>, equal_to</*iter-key-type*/<InputIt>>, Allocator>; template<class InputIt, class Hash, class Allocator> unordered_multimap(InputIt, InputIt, typename /* see description */::size_type, Hash, Allocator) -> unordered_multimap</*iter-key-type*/<InputIt>, iter-mapped-type<InputIt>, Hash, equal_to</*iter-key-type*/<InputIt>>, Allocator>; template<class Key, class T, class Allocator> unordered_multimap(initializer_list<pair<Key, T>>, typename /* see description */::size_type, Allocator) -> unordered_multimap<Key, T, hash<Key>, equal_to<Key>, Allocator>; template<class Key, class T, class Allocator> unordered_multimap(initializer_list<pair<Key, T>>, Allocator) -> unordered_multimap<Key, T, hash<Key>, equal_to<Key>, Allocator>; template<class Key, class T, class Hash, class Allocator> unordered_multimap(initializer_list<pair<Key, T>>, typename /* see description */::size_type, Hash, Allocator) -> unordered_multimap<Key, T, Hash, equal_to<Key>, Allocator>; // swap template<class Key, class T, class Hash, class Pred, class Alloc> void swap(unordered_multimap<Key, T, Hash, Pred, Alloc>& x, unordered_multimap<Key, T, Hash, Pred, Alloc>& y) noexcept(noexcept(x.swap(y))); } ```
programming_docs
cpp Standard library header <random> (C++11) Standard library header <random> (C++11) ======================================== This header is part of the [pseudo-random number generation](../numeric/random "cpp/numeric/random") library. | | | --- | | Includes | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Concepts | | Uniform random bit generator requirements | | [uniform\_random\_bit\_generator](../numeric/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) | | Classes | | Random number engines | | [linear\_congruential\_engine](../numeric/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](../numeric/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](../numeric/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 | | [discard\_block\_engine](../numeric/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](../numeric/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](../numeric/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 generators | | `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 | | [random\_device](../numeric/random/random_device "cpp/numeric/random/random device") (C++11) | non-deterministic random number generator using hardware entropy source (class) | | Uniform distributions | | [uniform\_int\_distribution](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/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](../numeric/random/discrete_distribution "cpp/numeric/random/discrete distribution") (C++11) | produces random integers on a discrete distribution. (class template) | | [piecewise\_constant\_distribution](../numeric/random/piecewise_constant_distribution "cpp/numeric/random/piecewise constant distribution") (C++11) | produces real values distributed on constant subintervals. (class template) | | [piecewise\_linear\_distribution](../numeric/random/piecewise_linear_distribution "cpp/numeric/random/piecewise linear distribution") (C++11) | produces real values distributed on defined subintervals. (class template) | | Utilities | | [seed\_seq](../numeric/random/seed_seq "cpp/numeric/random/seed seq") (C++11) | general-purpose bias-eliminating scrambled seed sequence generator (class) | | Functions | | [generate\_canonical](../numeric/random/generate_canonical "cpp/numeric/random/generate canonical") (C++11) | evenly distributes real values of given precision across [0, 1) (function template) | ### Synopsis ``` #include <initializer_list> namespace std { // uniform random bit generator requirements template<class G> concept uniform_random_bit_generator = /* see description */; // class template linear_congruential_engine template<class UIntType, UIntType a, UIntType c, UIntType m> class linear_congruential_engine; // class template mersenne_twister_engine template<class UIntType, size_t w, size_t n, size_t m, size_t r, UIntType a, size_t u, UIntType d, size_t s, UIntType b, size_t t, UIntType c, size_t l, UIntType f> class mersenne_twister_engine; // class template subtract_with_carry_engine template<class UIntType, size_t w, size_t s, size_t r> class subtract_with_carry_engine; // class template discard_block_engine template<class Engine, size_t p, size_t r> class discard_block_engine; // class template independent_bits_engine template<class Engine, size_t w, class UIntType> class independent_bits_engine; // class template shuffle_order_engine template<class Engine, size_t k> class shuffle_order_engine; // engines and engine adaptors with predefined parameters using minstd_rand0 = /* see description */; using minstd_rand = /* see description */; using mt19937 = /* see description */; using mt19937_64 = /* see description */; using ranlux24_base = /* see description */; using ranlux48_base = /* see description */; using ranlux24 = /* see description */; using ranlux48 = /* see description */; using knuth_b = /* see description */; using default_random_engine = /* see description */; // class random_device class random_device; // class seed_seq class seed_seq; // function template generate_canonical template<class RealType, size_t bits, class URBG> RealType generate_canonical(URBG& g); // class template uniform_int_distribution template<class IntType = int> class uniform_int_distribution; // class template uniform_real_distribution template<class RealType = double> class uniform_real_distribution; // class bernoulli_distribution class bernoulli_distribution; // class template binomial_distribution template<class IntType = int> class binomial_distribution; // class template geometric_distribution template<class IntType = int> class geometric_distribution; // class template negative_binomial_distribution template<class IntType = int> class negative_binomial_distribution; // class template poisson_distribution template<class IntType = int> class poisson_distribution; // class template exponential_distribution template<class RealType = double> class exponential_distribution; // class template gamma_distribution template<class RealType = double> class gamma_distribution; // class template weibull_distribution template<class RealType = double> class weibull_distribution; // class template extreme_value_distribution template<class RealType = double> class extreme_value_distribution; // class template normal_distribution template<class RealType = double> class normal_distribution; // class template lognormal_distribution template<class RealType = double> class lognormal_distribution; // class template chi_squared_distribution template<class RealType = double> class chi_squared_distribution; // class template cauchy_distribution template<class RealType = double> class cauchy_distribution; // class template fisher_f_distribution template<class RealType = double> class fisher_f_distribution; // class template student_t_distribution template<class RealType = double> class student_t_distribution; // class template discrete_distribution template<class IntType = int> class discrete_distribution; // class template piecewise_constant_distribution template<class RealType = double> class piecewise_constant_distribution; // class template piecewise_linear_distribution template<class RealType = double> class piecewise_linear_distribution; } ``` #### Concept [`uniform_random_bit_generator`](../numeric/random/uniform_random_bit_generator "cpp/numeric/random/uniform random bit generator") ``` namespace std { template<class G> concept uniform_random_bit_generator = invocable<G&> && unsigned_integral<invoke_result_t<G&>> && requires { { G::min() } -> same_as<invoke_result_t<G&>>; { G::max() } -> same_as<invoke_result_t<G&>>; requires bool_constant<(G::min() < G::max())>::value; }; } ``` #### Class template `[std::linear\_congruential\_engine](../numeric/random/linear_congruential_engine "cpp/numeric/random/linear congruential engine")` ``` namespace std { template<class UIntType, UIntType a, UIntType c, UIntType m> class linear_congruential_engine { public: // types using result_type = UIntType; // engine characteristics static constexpr result_type multiplier = a; static constexpr result_type increment = c; static constexpr result_type modulus = m; static constexpr result_type min() { return c == 0u ? 1u: 0u; } static constexpr result_type max() { return m - 1u; } static constexpr result_type default_seed = 1u; // constructors and seeding functions linear_congruential_engine() : linear_congruential_engine(default_seed) {} explicit linear_congruential_engine(result_type s); template<class Sseq> explicit linear_congruential_engine(Sseq& q); void seed(result_type s = default_seed); template<class Sseq> void seed(Sseq& q); // equality operators friend bool operator==(const linear_congruential_engine& x, const linear_congruential_engine& y); // generating functions result_type operator()(); void discard(unsigned long long z); // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const linear_congruential_engine& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, linear_congruential_engine& x); }; } ``` #### Class template `[std::mersenne\_twister\_engine](../numeric/random/mersenne_twister_engine "cpp/numeric/random/mersenne twister engine")` ``` namespace std { template<class UIntType, size_t w, size_t n, size_t m, size_t r, UIntType a, size_t u, UIntType d, size_t s, UIntType b, size_t t, UIntType c, size_t l, UIntType f> class mersenne_twister_engine { public: // types using result_type = UIntType; // engine characteristics static constexpr size_t word_size = w; static constexpr size_t state_size = n; static constexpr size_t shift_size = m; static constexpr size_t mask_bits = r; static constexpr UIntType xor_mask = a; static constexpr size_t tempering_u = u; static constexpr UIntType tempering_d = d; static constexpr size_t tempering_s = s; static constexpr UIntType tempering_b = b; static constexpr size_t tempering_t = t; static constexpr UIntType tempering_c = c; static constexpr size_t tempering_l = l; static constexpr UIntType initialization_multiplier = f; static constexpr result_type min() { return 0; } static constexpr result_type max() { return /* pow(2, w) - 1 */; } static constexpr result_type default_seed = 5489u; // constructors and seeding functions mersenne_twister_engine() : mersenne_twister_engine(default_seed) {} explicit mersenne_twister_engine(result_type value); template<class Sseq> explicit mersenne_twister_engine(Sseq& q); void seed(result_type value = default_seed); template<class Sseq> void seed(Sseq& q); // equality operators friend bool operator==(const mersenne_twister_engine& x, const mersenne_twister_engine& y); // generating functions result_type operator()(); void discard(unsigned long long z); // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const mersenne_twister_engine& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, mersenne_twister_engine& x); }; } ``` #### Class template `[std::subtract\_with\_carry\_engine](../numeric/random/subtract_with_carry_engine "cpp/numeric/random/subtract with carry engine")` ``` namespace std { template<class UIntType, size_t w, size_t s, size_t r> class subtract_with_carry_engine { public: // types using result_type = UIntType; // engine characteristics static constexpr size_t word_size = w; static constexpr size_t short_lag = s; static constexpr size_t long_lag = r; static constexpr result_type min() { return 0; } static constexpr result_type max() { return /* pow(2, w) - 1 */; } static constexpr result_type default_seed = 19780503u; // constructors and seeding functions subtract_with_carry_engine() : subtract_with_carry_engine(default_seed) {} explicit subtract_with_carry_engine(result_type value); template<class Sseq> explicit subtract_with_carry_engine(Sseq& q); void seed(result_type value = default_seed); template<class Sseq> void seed(Sseq& q); // equality operators friend bool operator==(const subtract_with_carry_engine& x, const subtract_with_carry_engine& y); // generating functions result_type operator()(); void discard(unsigned long long z); // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const subtract_with_carry_engine& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, subtract_with_carry_engine& x); }; } ``` #### Class template `[std::discard\_block\_engine](../numeric/random/discard_block_engine "cpp/numeric/random/discard block engine")` ``` namespace std { template<class Engine, size_t p, size_t r> class discard_block_engine { public: // types using result_type = typename Engine::result_type; // engine characteristics static constexpr size_t block_size = p; static constexpr size_t used_block = r; static constexpr result_type min() { return Engine::min(); } static constexpr result_type max() { return Engine::max(); } // constructors and seeding functions discard_block_engine(); explicit discard_block_engine(const Engine& e); explicit discard_block_engine(Engine&& e); explicit discard_block_engine(result_type s); template<class Sseq> explicit discard_block_engine(Sseq& q); void seed(); void seed(result_type s); template<class Sseq> void seed(Sseq& q); // equality operators friend bool operator==(const discard_block_engine& x, const discard_block_engine& y); // generating functions result_type operator()(); void discard(unsigned long long z); // property functions const Engine& base() const noexcept { return e; }; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const discard_block_engine& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, discard_block_engine& x); private: Engine e; // exposition only int n; // exposition only }; } ``` #### Class template `[std::independent\_bits\_engine](../numeric/random/independent_bits_engine "cpp/numeric/random/independent bits engine")` ``` namespace std { template<class Engine, size_t w, class UIntType> class independent_bits_engine { public: // types using result_type = UIntType; // engine characteristics static constexpr result_type min() { return 0; } static constexpr result_type max() { return /* pow(2, w) - 1 */; } // constructors and seeding functions independent_bits_engine(); explicit independent_bits_engine(const Engine& e); explicit independent_bits_engine(Engine&& e); explicit independent_bits_engine(result_type s); template<class Sseq> explicit independent_bits_engine(Sseq& q); void seed(); void seed(result_type s); template<class Sseq> void seed(Sseq& q); // equality operators friend bool operator==(const independent_bits_engine& x, const independent_bits_engine& y); // generating functions result_type operator()(); void discard(unsigned long long z); // property functions const Engine& base() const noexcept { return e; }; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const independent_bits_engine& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, independent_bits_engine& x); private: Engine e; // exposition only }; } ``` #### Class template `[std::shuffle\_order\_engine](../numeric/random/shuffle_order_engine "cpp/numeric/random/shuffle order engine")` ``` namespace std { template<class Engine, size_t k> class shuffle_order_engine { public: // types using result_type = typename Engine::result_type; // engine characteristics static constexpr size_t table_size = k; static constexpr result_type min() { return Engine::min(); } static constexpr result_type max() { return Engine::max(); } // constructors and seeding functions shuffle_order_engine(); explicit shuffle_order_engine(const Engine& e); explicit shuffle_order_engine(Engine&& e); explicit shuffle_order_engine(result_type s); template<class Sseq> explicit shuffle_order_engine(Sseq& q); void seed(); void seed(result_type s); template<class Sseq> void seed(Sseq& q); // equality operators friend bool operator==(const shuffle_order_engine& x, const shuffle_order_engine& y); // generating functions result_type operator()(); void discard(unsigned long long z); // property functions const Engine& base() const noexcept { return e; }; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const shuffle_order_engine& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, shuffle_order_engine& x); private: Engine e; // exposition only result_type V[k]; // exposition only result_type Y; // exposition only }; } ``` #### Engines and engine adaptors with predefined parameters ``` namespace std { using minstd_rand0 = linear_congruential_engine<uint_fast32_t, 16'807, 0, 2'147'483'647>; using minstd_rand = linear_congruential_engine<uint_fast32_t, 48'271, 0, 2'147'483'647>; using mt19937 = mersenne_twister_engine<uint_fast32_t, 32, 624, 397, 31, 0x9908'b0df, 11, 0xffff'ffff, 7, 0x9d2c'5680, 15, 0xefc6'0000, 18, 1'812'433'253>; //' using mt19937_64 = mersenne_twister_engine<uint_fast64_t, 64, 312, 156, 31, 0xb502'6f5a'a966'19e9, 29, 0x5555'5555'5555'5555, 17, 0x71d6'7fff'eda6'0000, 37, 0xfff7'eee0'0000'0000, 43, 6'364'136'223'846'793'005>; //' using ranlux24_base = subtract_with_carry_engine<uint_fast32_t, 24, 10, 24>; using ranlux48_base = subtract_with_carry_engine<uint_fast64_t, 48, 5, 12>; using ranlux24 = discard_block_engine<ranlux24_base, 223, 23>; using ranlux48 = discard_block_engine<ranlux48_base, 389, 11>; using knuth_b = shuffle_order_engine<minstd_rand0,256>; using default_random_engine = /* implementation-defined */; } ``` #### Class `[std::random\_device](../numeric/random/random_device "cpp/numeric/random/random device")` ``` namespace std { class random_device { public: // types using result_type = unsigned int; // generator characteristics static constexpr result_type min() { return numeric_limits<result_type>::min(); } static constexpr result_type max() { return numeric_limits<result_type>::max(); } // constructors random_device() : random_device(/* implementation-defined */) {} explicit random_device(const string& token); // generating functions result_type operator()(); // property functions double entropy() const noexcept; // no copy functions random_device(const random_device&) = delete; void operator=(const random_device&) = delete; }; } ``` #### Class `[std::seed\_seq](../numeric/random/seed_seq "cpp/numeric/random/seed seq")` ``` namespace std { class seed_seq { public: // types using result_type = uint_least32_t; // constructors seed_seq() noexcept; template<class T> seed_seq(initializer_list<T> il); template<class InputIt> seed_seq(InputIt begin, InputIt end); // generating functions template<class RandomAccessIt> void generate(RandomAccessIt begin, RandomAccessIt end); // property functions size_t size() const noexcept; template<class OutputIt> void param(OutputIt dest) const; // no copy functions seed_seq(const seed_seq&) = delete; void operator=(const seed_seq&) = delete; private: vector<result_type> v; // exposition only }; } ``` #### Class template `[std::uniform\_int\_distribution](../numeric/random/uniform_int_distribution "cpp/numeric/random/uniform int distribution")` ``` namespace std { template<class IntType = int> class uniform_int_distribution { public: // types using result_type = IntType; using param_type = /* unspecified */; // constructors and reset functions uniform_int_distribution() : uniform_int_distribution(0) {} explicit uniform_int_distribution(IntType a, IntType b = numeric_limits<IntType>::max()); explicit uniform_int_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const uniform_int_distribution& x, const uniform_int_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions result_type a() const; result_type b() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const uniform_int_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, uniform_int_distribution& x); }; } ``` #### Class template `[std::uniform\_real\_distribution](../numeric/random/uniform_real_distribution "cpp/numeric/random/uniform real distribution")` ``` namespace std { template<class RealType = double> class uniform_real_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions uniform_real_distribution() : uniform_real_distribution(0.0) {} explicit uniform_real_distribution(RealType a, RealType b = 1.0); explicit uniform_real_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const uniform_real_distribution& x, const uniform_real_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions result_type a() const; result_type b() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const uniform_real_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, uniform_real_distribution& x); }; } ``` #### Class `[std::bernoulli\_distribution](../numeric/random/bernoulli_distribution "cpp/numeric/random/bernoulli distribution")` ``` namespace std { class bernoulli_distribution { public: // types using result_type = bool; using param_type = /* unspecified */; // constructors and reset functions bernoulli_distribution() : bernoulli_distribution(0.5) {} explicit bernoulli_distribution(double p); explicit bernoulli_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const bernoulli_distribution& x, const bernoulli_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions double p() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const bernoulli_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, bernoulli_distribution& x); }; } ``` #### Class template `[std::binomial\_distribution](../numeric/random/binomial_distribution "cpp/numeric/random/binomial distribution")` ``` namespace std { template<class IntType = int> class binomial_distribution { public: // types using result_type = IntType; using param_type = /* unspecified */; // constructors and reset functions binomial_distribution() : binomial_distribution(1) {} explicit binomial_distribution(IntType t, double p = 0.5); explicit binomial_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const binomial_distribution& x, const binomial_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions IntType t() const; double p() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const binomial_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, binomial_distribution& x); }; } ``` #### Class template `[std::geometric\_distribution](../numeric/random/geometric_distribution "cpp/numeric/random/geometric distribution")` ``` namespace std { template<class IntType = int> class geometric_distribution { public: // types using result_type = IntType; using param_type = /* unspecified */; // constructors and reset functions geometric_distribution() : geometric_distribution(0.5) {} explicit geometric_distribution(double p); explicit geometric_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const geometric_distribution& x, const geometric_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions double p() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const geometric_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, geometric_distribution& x); }; } ``` #### Class template `[std::negative\_binomial\_distribution](../numeric/random/negative_binomial_distribution "cpp/numeric/random/negative binomial distribution")` ``` namespace std { template<class IntType = int> class negative_binomial_distribution { public: // types using result_type = IntType; using param_type = /* unspecified */; // constructors and reset functions negative_binomial_distribution() : negative_binomial_distribution(1) {} explicit negative_binomial_distribution(IntType k, double p = 0.5); explicit negative_binomial_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const negative_binomial_distribution& x, const negative_binomial_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions IntType k() const; double p() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const negative_binomial_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, negative_binomial_distribution& x); }; } ``` #### Class template `[std::poisson\_distribution](../numeric/random/poisson_distribution "cpp/numeric/random/poisson distribution")` ``` namespace std { template<class IntType = int> class poisson_distribution { public: // types using result_type = IntType; using param_type = /* unspecified */; // constructors and reset functions poisson_distribution() : poisson_distribution(1.0) {} explicit poisson_distribution(double mean); explicit poisson_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const poisson_distribution& x, const poisson_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions double mean() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const poisson_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, poisson_distribution& x); }; } ``` #### Class template `[std::exponential\_distribution](../numeric/random/exponential_distribution "cpp/numeric/random/exponential distribution")` ``` namespace std { template<class RealType = double> class exponential_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions exponential_distribution() : exponential_distribution(1.0) {} explicit exponential_distribution(RealType lambda); explicit exponential_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const exponential_distribution& x, const exponential_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType lambda() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const exponential_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, exponential_distribution& x); }; } ``` #### Class template `[std::gamma\_distribution](../numeric/random/gamma_distribution "cpp/numeric/random/gamma distribution")` ``` namespace std { template<class RealType = double> class gamma_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions gamma_distribution() : gamma_distribution(1.0) {} explicit gamma_distribution(RealType alpha, RealType beta = 1.0); explicit gamma_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const gamma_distribution& x, const gamma_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType alpha() const; RealType beta() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const gamma_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, gamma_distribution& x); }; } ``` #### Class template `[std::weibull\_distribution](../numeric/random/weibull_distribution "cpp/numeric/random/weibull distribution")` ``` namespace std { template<class RealType = double> class weibull_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions weibull_distribution() : weibull_distribution(1.0) {} explicit weibull_distribution(RealType a, RealType b = 1.0); explicit weibull_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const weibull_distribution& x, const weibull_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType a() const; RealType b() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const weibull_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, weibull_distribution& x); }; } ``` #### Class template `[std::extreme\_value\_distribution](../numeric/random/extreme_value_distribution "cpp/numeric/random/extreme value distribution")` ``` namespace std { template<class RealType = double> class extreme_value_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions extreme_value_distribution() : extreme_value_distribution(0.0) {} explicit extreme_value_distribution(RealType a, RealType b = 1.0); explicit extreme_value_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const extreme_value_distribution& x, const extreme_value_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType a() const; RealType b() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const extreme_value_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, extreme_value_distribution& x); }; } ``` #### Class template `[std::normal\_distribution](../numeric/random/normal_distribution "cpp/numeric/random/normal distribution")` ``` namespace std { template<class RealType = double> class normal_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions normal_distribution() : normal_distribution(0.0) {} explicit normal_distribution(RealType mean, RealType stddev = 1.0); explicit normal_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const normal_distribution& x, const normal_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType mean() const; RealType stddev() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const normal_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, normal_distribution& x); }; } ``` #### Class template `[std::lognormal\_distribution](../numeric/random/lognormal_distribution "cpp/numeric/random/lognormal distribution")` ``` namespace std { template<class RealType = double> class lognormal_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions lognormal_distribution() : lognormal_distribution(0.0) {} explicit lognormal_distribution(RealType m, RealType s = 1.0); explicit lognormal_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const lognormal_distribution& x, const lognormal_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType m() const; RealType s() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const lognormal_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, lognormal_distribution& x); }; } ``` #### Class template `[std::chi\_squared\_distribution](../numeric/random/chi_squared_distribution "cpp/numeric/random/chi squared distribution")` ``` namespace std { template<class RealType = double> class chi_squared_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions chi_squared_distribution() : chi_squared_distribution(1.0) {} explicit chi_squared_distribution(RealType n); explicit chi_squared_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const chi_squared_distribution& x, const chi_squared_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType n() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const chi_squared_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, chi_squared_distribution& x); }; } ``` #### Class template `[std::cauchy\_distribution](../numeric/random/cauchy_distribution "cpp/numeric/random/cauchy distribution")` ``` namespace std { template<class RealType = double> class cauchy_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions cauchy_distribution() : cauchy_distribution(0.0) {} explicit cauchy_distribution(RealType a, RealType b = 1.0); explicit cauchy_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const cauchy_distribution& x, const cauchy_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType a() const; RealType b() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const cauchy_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, cauchy_distribution& x); }; ``` #### Class template `[std::fisher\_f\_distribution](../numeric/random/fisher_f_distribution "cpp/numeric/random/fisher f distribution")` ``` namespace std { template<class RealType = double> class fisher_f_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions fisher_f_distribution() : fisher_f_distribution(1.0) {} explicit fisher_f_distribution(RealType m, RealType n = 1.0); explicit fisher_f_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const fisher_f_distribution& x, const fisher_f_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType m() const; RealType n() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const fisher_f_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, fisher_f_distribution& x); }; } ``` #### Class template `[std::student\_t\_distribution](../numeric/random/student_t_distribution "cpp/numeric/random/student t distribution")` ``` namespace std { template<class RealType = double> class student_t_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions student_t_distribution() : student_t_distribution(1.0) {} explicit student_t_distribution(RealType n); explicit student_t_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const student_t_distribution& x, const student_t_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions RealType n() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const student_t_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, student_t_distribution& x); }; } ``` #### Class template `[std::discrete\_distribution](../numeric/random/discrete_distribution "cpp/numeric/random/discrete distribution")` ``` namespace std { template<class IntType = int> class discrete_distribution { public: // types using result_type = IntType; using param_type = /* unspecified */; // constructors and reset functions discrete_distribution(); template<class InputIt> discrete_distribution(InputIt firstW, InputIt lastW); discrete_distribution(initializer_list<double> wl); template<class UnaryOperation> discrete_distribution(size_t nw, double xmin, double xmax, UnaryOperation fw); explicit discrete_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const discrete_distribution& x, const discrete_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions vector<double> probabilities() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const discrete_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, discrete_distribution& x); }; } ``` #### Class template `[std::piecewise\_constant\_distribution](../numeric/random/piecewise_constant_distribution "cpp/numeric/random/piecewise constant distribution")` ``` namespace std { template<class RealType = double> class piecewise_constant_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions piecewise_constant_distribution(); template<class InputItB, class InputItW> piecewise_constant_distribution(InputItB firstB, InputItB lastB, InputItW firstW); template<class UnaryOperation> piecewise_constant_distribution(initializer_list<RealType> bl, UnaryOperation fw); template<class UnaryOperation> piecewise_constant_distribution(size_t nw, RealType xmin, RealType xmax, UnaryOperation fw); explicit piecewise_constant_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const piecewise_constant_distribution& x, const piecewise_constant_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions vector<result_type> intervals() const; vector<result_type> densities() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const piecewise_constant_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, piecewise_constant_distribution& x); }; } ``` #### Class template `[std::piecewise\_linear\_distribution](../numeric/random/piecewise_linear_distribution "cpp/numeric/random/piecewise linear distribution")` ``` namespace std { template<class RealType = double> class piecewise_linear_distribution { public: // types using result_type = RealType; using param_type = /* unspecified */; // constructors and reset functions piecewise_linear_distribution(); template<class InputItB, class InputItW> piecewise_linear_distribution(InputItB firstB, InputItB lastB, InputItW firstW); template<class UnaryOperation> piecewise_linear_distribution(initializer_list<RealType> bl, UnaryOperation fw); template<class UnaryOperation> piecewise_linear_distribution(size_t nw, RealType xmin, RealType xmax, UnaryOperation fw); explicit piecewise_linear_distribution(const param_type& parm); void reset(); // equality operators friend bool operator==(const piecewise_linear_distribution& x, const piecewise_linear_distribution& y); // generating functions template<class URBG> result_type operator()(URBG& g); template<class URBG> result_type operator()(URBG& g, const param_type& parm); // property functions vector<result_type> intervals() const; vector<result_type> densities() const; param_type param() const; void param(const param_type& parm); result_type min() const; result_type max() const; // inserters and extractors template<class charT, class traits> friend basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const piecewise_linear_distribution& x); template<class charT, class traits> friend basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>& is, piecewise_linear_distribution& x); }; } ```
programming_docs
cpp Standard library header <stop_token> (C++20) Standard library header <stop\_token> (C++20) ============================================= This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [stop\_token](../thread/stop_token "cpp/thread/stop token") (C++20) | an interface for querying if a `[std::jthread](../thread/jthread "cpp/thread/jthread")` cancellation request has been made (class) | | [stop\_source](../thread/stop_source "cpp/thread/stop source") (C++20) | class representing a request to stop one or more `[std::jthread](../thread/jthread "cpp/thread/jthread")`s (class) | | [stop\_callback](../thread/stop_callback "cpp/thread/stop callback") (C++20) | an interface for registering callbacks on `[std::jthread](../thread/jthread "cpp/thread/jthread")` cancellation (class template) | | [nostopstate\_t](../thread/stop_source/nostopstate_t "cpp/thread/stop source/nostopstate t") (C++20) | placeholder type for use in `stop_source` constructor (class) | | Constants | | [nostopstate](../thread/stop_source/nostopstate "cpp/thread/stop source/nostopstate") (C++20) | a `std::nostopstate_t` instance for use in `stop_source` constructor (constant) | ### Synopsis ``` namespace std { // class stop_token class stop_token; // class stop_source class stop_source; // no-shared-stop-state indicator struct nostopstate_t { explicit nostopstate_t() = default; }; inline constexpr nostopstate_t nostopstate{}; // class stop_callback template<class Callback> class stop_callback; } ``` #### Class `[std::stop\_token](../thread/stop_token "cpp/thread/stop token")` ``` namespace std { class stop_token { public: // constructors, copy, and assignment stop_token() noexcept; stop_token(const stop_token&) noexcept; stop_token(stop_token&&) noexcept; stop_token& operator=(const stop_token&) noexcept; stop_token& operator=(stop_token&&) noexcept; ~stop_token(); void swap(stop_token&) noexcept; // stop handling [[nodiscard]] bool stop_requested() const noexcept; [[nodiscard]] bool stop_possible() const noexcept; [[nodiscard]] friend bool operator==(const stop_token& lhs, const stop_token& rhs) noexcept; friend void swap(stop_token& lhs, stop_token& rhs) noexcept; }; } ``` #### Class `[std::stop\_source](../thread/stop_source "cpp/thread/stop source")` ``` namespace std { // no-shared-stop-state indicator struct nostopstate_t { explicit nostopstate_t() = default; }; inline constexpr nostopstate_t nostopstate{}; class stop_source { public: // constructors, copy, and assignment stop_source(); explicit stop_source(nostopstate_t) noexcept; stop_source(const stop_source&) noexcept; stop_source(stop_source&&) noexcept; stop_source& operator=(const stop_source&) noexcept; stop_source& operator=(stop_source&&) noexcept; ~stop_source(); void swap(stop_source&) noexcept; // stop handling [[nodiscard]] stop_token get_token() const noexcept; [[nodiscard]] bool stop_possible() const noexcept; [[nodiscard]] bool stop_requested() const noexcept; bool request_stop() noexcept; [[nodiscard]] friend bool operator==(const stop_source& lhs, const stop_source& rhs) noexcept; friend void swap(stop_source& lhs, stop_source& rhs) noexcept; }; } ``` #### Class template `[std::stop\_callback](../thread/stop_callback "cpp/thread/stop callback")` ``` namespace std { template<class Callback> class stop_callback { public: using callback_type = Callback; // constructors and destructor template<class C> explicit stop_callback(const stop_token& st, C&& cb) noexcept(is_nothrow_constructible_v<Callback, C>); template<class C> explicit stop_callback(stop_token&& st, C&& cb) noexcept(is_nothrow_constructible_v<Callback, C>); ~stop_callback(); stop_callback(const stop_callback&) = delete; stop_callback(stop_callback&&) = delete; stop_callback& operator=(const stop_callback&) = delete; stop_callback& operator=(stop_callback&&) = delete; private: Callback callback; // exposition only }; template<class Callback> stop_callback(stop_token, Callback) -> stop_callback<Callback>; } ``` cpp Standard library header <initializer_list> (C++11) Standard library header <initializer\_list> (C++11) =================================================== This header is part of the [utility](../utility "cpp/utility") library. | | | --- | | Classes | | [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) | | Functions | | [std::begin(std::initializer\_list)](../utility/initializer_list/begin2 "cpp/utility/initializer list/begin2") (C++11) | overloads `[std::begin](../iterator/begin "cpp/iterator/begin")` (function template) | | [std::end(std::initializer\_list)](../utility/initializer_list/end2 "cpp/utility/initializer list/end2") (C++11) | specializes `[std::end](../iterator/end "cpp/iterator/end")` (function template) | ### Synopsis ``` // all freestanding namespace std { template<class E> class initializer_list { public: using value_type = E; using reference = const E&; using const_reference = const E&; using size_type = size_t; using iterator = const E*; using const_iterator = const E*; constexpr initializer_list() noexcept; constexpr size_t size() const noexcept; // number of elements constexpr const E* begin() const noexcept; // first element constexpr const E* end() const noexcept; // one past the last element }; // initializer list range access template<class E> constexpr const E* begin(initializer_list<E> il) noexcept; template<class E> constexpr const E* end(initializer_list<E> il) noexcept; } ``` cpp Standard library header <locale> Standard library header <locale> ================================ This header is part of the [localization](../locale "cpp/locale") library. | | | --- | | Classes | | [locale](../locale/locale "cpp/locale/locale") | set of polymorphic facets that encapsulate cultural differences (class) | | String and stream conversions | | [wstring\_convert](../locale/wstring_convert "cpp/locale/wstring convert") (C++11)(deprecated in C++17) | performs conversions between a wide string and a byte string (class template) | | [wbuffer\_convert](../locale/wbuffer_convert "cpp/locale/wbuffer convert") (C++11)(deprecated in C++17) | performs conversion between a byte stream buffer and a wide stream buffer (class template) | | Facet category base classes | | [ctype\_base](../locale/ctype_base "cpp/locale/ctype base") | defines character classification categories (class) | | [codecvt\_base](../locale/codecvt_base "cpp/locale/codecvt base") | defines character conversion errors (class) | | [messages\_base](../locale/messages_base "cpp/locale/messages base") | defines messages catalog type (class) | | [time\_base](../locale/time_base "cpp/locale/time base") | defines date format constants (class) | | [money\_base](../locale/money_base "cpp/locale/money base") | defines monetary formatting patterns (class) | | Facet categories | | [ctype](../locale/ctype "cpp/locale/ctype") | defines character classification tables (class template) | | [ctype<char>](../locale/ctype_char "cpp/locale/ctype char") | specialization of `[std::ctype](../locale/ctype "cpp/locale/ctype")` for type `char` (class template specialization) | | [codecvt](../locale/codecvt "cpp/locale/codecvt") | converts between character encodings, including UTF-8, UTF-16, UTF-32 (class template) | | [collate](../locale/collate "cpp/locale/collate") | defines lexicographical comparison and hashing of strings (class template) | | [messages](../locale/messages "cpp/locale/messages") | implements retrieval of strings from message catalogs (class template) | | [time\_get](../locale/time_get "cpp/locale/time get") | parses time/date values from an input character sequence into `struct [std::tm](http://en.cppreference.com/w/cpp/chrono/c/tm)` (class template) | | [time\_put](../locale/time_put "cpp/locale/time put") | formats contents of `struct [std::tm](http://en.cppreference.com/w/cpp/chrono/c/tm)` for output as character sequence (class template) | | [num\_get](../locale/num_get "cpp/locale/num get") | parses numeric values from an input character sequence (class template) | | [num\_put](../locale/num_put "cpp/locale/num put") | formats numeric values for output as character sequence (class template) | | [numpunct](../locale/numpunct "cpp/locale/numpunct") | defines numeric punctuation rules (class template) | | [money\_get](../locale/money_get "cpp/locale/money get") | parses and constructs a monetary value from an input character sequence (class template) | | [money\_put](../locale/money_put "cpp/locale/money put") | formats a monetary value for output as a character sequence (class template) | | [moneypunct](../locale/moneypunct "cpp/locale/moneypunct") | defines monetary formatting parameters used by `[std::money\_get](../locale/money_get "cpp/locale/money get")` and `[std::money\_put](../locale/money_put "cpp/locale/money put")` (class template) | | Locale-specific facet categories | | [ctype\_byname](../locale/ctype_byname "cpp/locale/ctype byname") | represents the system-supplied `[std::ctype](../locale/ctype "cpp/locale/ctype")` for the named locale (class template) | | [codecvt\_byname](../locale/codecvt_byname "cpp/locale/codecvt byname") | represents the system-supplied `[std::codecvt](../locale/codecvt "cpp/locale/codecvt")` for the named locale (class template) | | [messages\_byname](../locale/messages_byname "cpp/locale/messages byname") | represents the system-supplied `[std::messages](../locale/messages "cpp/locale/messages")` for the named locale (class template) | | [collate\_byname](../locale/collate_byname "cpp/locale/collate byname") | represents the system-supplied `[std::collate](../locale/collate "cpp/locale/collate")` for the named locale (class template) | | [time\_get\_byname](../locale/time_get_byname "cpp/locale/time get byname") | represents the system-supplied `[std::time\_get](../locale/time_get "cpp/locale/time get")` for the named locale (class template) | | [time\_put\_byname](../locale/time_put_byname "cpp/locale/time put byname") | represents the system-supplied `[std::time\_put](../locale/time_put "cpp/locale/time put")` for the named locale (class template) | | [numpunct\_byname](../locale/numpunct_byname "cpp/locale/numpunct byname") | represents the system-supplied `[std::numpunct](../locale/numpunct "cpp/locale/numpunct")` for the named locale (class template) | | [moneypunct\_byname](../locale/moneypunct_byname "cpp/locale/moneypunct byname") | represents the system-supplied `[std::moneypunct](../locale/moneypunct "cpp/locale/moneypunct")` for the named locale (class template) | | Functions | | Locales and facets | | [use\_facet](../locale/use_facet "cpp/locale/use facet") | obtains a facet from a locale (function template) | | [has\_facet](../locale/has_facet "cpp/locale/has facet") | checks if a locale implements a specific facet (function template) | | Character classification | | [isspace(std::locale)](../locale/isspace "cpp/locale/isspace") | checks if a character is classified as whitespace by a locale (function template) | | [isblank(std::locale)](../locale/isblank "cpp/locale/isblank") (C++11) | checks if a character is classified as a blank character by a locale (function template) | | [iscntrl(std::locale)](../locale/iscntrl "cpp/locale/iscntrl") | checks if a character is classified as a control character by a locale (function template) | | [isupper(std::locale)](../locale/isupper "cpp/locale/isupper") | checks if a character is classified as uppercase by a locale (function template) | | [islower(std::locale)](../locale/islower "cpp/locale/islower") | checks if a character is classified as lowercase by a locale (function template) | | [isalpha(std::locale)](../locale/isalpha "cpp/locale/isalpha") | checks if a character is classified as alphabetic by a locale (function template) | | [isdigit(std::locale)](../locale/isdigit "cpp/locale/isdigit") | checks if a character is classified as a digit by a locale (function template) | | [ispunct(std::locale)](../locale/ispunct "cpp/locale/ispunct") | checks if a character is classified as punctuation by a locale (function template) | | [isxdigit(std::locale)](../locale/isxdigit "cpp/locale/isxdigit") | checks if a character is classified as a hexadecimal digit by a locale (function template) | | [isalnum(std::locale)](../locale/isalnum "cpp/locale/isalnum") | checks if a character is classified as alphanumeric by a locale (function template) | | [isprint(std::locale)](../locale/isprint "cpp/locale/isprint") | checks if a character is classified as printable by a locale (function template) | | [isgraph(std::locale)](../locale/isgraph "cpp/locale/isgraph") | checks if a character is classfied as graphical by a locale (function template) | | Character conversions | | [toupper(std::locale)](../locale/toupper "cpp/locale/toupper") | converts a character to uppercase using the ctype facet of a locale (function template) | | [tolower(std::locale)](../locale/tolower "cpp/locale/tolower") | converts a character to lowercase using the ctype facet of a locale (function template) | #### Synopsis ``` namespace std { // locale: class locale; template <class Facet> const Facet& use_facet(const locale&); template <class Facet> bool has_facet(const locale&) noexcept; // convenience interfaces: template <class charT> bool isspace (charT c, const locale& loc); template <class charT> bool isprint (charT c, const locale& loc); template <class charT> bool iscntrl (charT c, const locale& loc); template <class charT> bool isupper (charT c, const locale& loc); template <class charT> bool islower (charT c, const locale& loc); template <class charT> bool isalpha (charT c, const locale& loc); template <class charT> bool isdigit (charT c, const locale& loc); template <class charT> bool ispunct (charT c, const locale& loc); template <class charT> bool isxdigit(charT c, const locale& loc); template <class charT> bool isalnum (charT c, const locale& loc); template <class charT> bool isgraph (charT c, const locale& loc); template <class charT> charT toupper(charT c, const locale& loc); template <class charT> charT tolower(charT c, const locale& loc); template <class Codecvt, class Elem = wchar_t, class Wide_alloc = std::allocator<Elem>, class Byte_alloc = std::allocator<char>> class wstring_convert; template <class Codecvt, class Elem = wchar_t, class Tr = char_traits<Elem>> class wbuffer_convert; // ctype: class ctype_base; template <class charT> class ctype; template <> class ctype<char>; // specialization template <class charT> class ctype_byname; class codecvt_base; template <class internT, class externT, class stateT> class codecvt; template <class internT, class externT, class stateT> class codecvt_byname; // numeric: template <class charT, class InputIterator = istreambuf_iterator<charT>> class num_get; template <class charT, class OutputIterator = osterambuf_iterator<charT>> class num_put; template <class charT> class numpunct; template <class charT> class numpunct_byname; // collation: template <class charT> class collate; template <class charT> class collate_byname; // date and time: class time_base; template <class charT, class InputIterator = istreambuf_iterator<charT>> class time_get; template <class charT, class InputIterator> = istreambuf_iterator<charT>> class time_get_byname; template <class charT, class OutputIterator> = ostreambuf_iterator<charT>> class time_put; template <class charT, class OutputIterator> = ostreambuf_iterator<charT>> class time_put_byname; // money: class money_base; template <class charT, class InputIterator = istreambuf_iterator<charT>> > class money_get; template <class charT, class OutputIterator = ostreambuf_iterator<charT>> > class money_put; template <class charT, bool Intl = false> class moneypunct; template <class charT, bool Intl = false> class moneypunct_byname; // message retrieval: class messages_base; template <class charT> class messages; template <class charT> class messages_byname; } ``` #### Class `[std::locale](../locale/locale "cpp/locale/locale")` ``` class locale { public: // types: class facet; class id; typedef int category; static const category // values assigned here are for exposition only none = 0, collate = 0x010, ctype = 0x020, monetary = 0x040, numeric = 0x080, time = 0x100, messages = 0x200, all = collate | ctype | monetary | numeric | time | messages; // construct/copy/destroy: locale() noexcept; locale(const locale& other) noexcept; explicit locale(const char* std_name); explicit locale(const string& std_name); locale(const locale& other, const char* std_name, category); locale(const locale& other, const string& std_name, category); template <class Facet> locale(const locale& other, Facet* f); locale(const locale& other, const locale& one, category); ~locale(); // not virtual const locale& operator=(const locale& other) noexcept; template <class Facet> locale combine(const locale& other) const; // locale operations: basic_string<char> name() const; bool operator==(const locale& other) const; bool operator!=(const locale& other) const; template <class charT, class traits, class Allocator> bool operator()(const basic_string<charT,traits,Allocator>& s1, const basic_string<charT,traits,Allocator>& s2) const; // global locale objects: static locale global(const locale&); static const locale& classic(); }; ``` #### Class `[std::ctype\_base](../locale/ctype_base "cpp/locale/ctype base")` ``` class ctype_base { public: typedef /*bitmask-type*/ mask; // numeric values are for exposition only. static const mask space = 1 << 0; static const mask print = 1 << 1; static const mask cntrl = 1 << 2; static const mask upper = 1 << 3; static const mask lower = 1 << 4; static const mask alpha = 1 << 5; static const mask digit = 1 << 6; static const mask punct = 1 << 7; static const mask xdigit= 1 << 8; static const mask blank = 1 << 9; static const mask alnum = alpha | digit; static const mask graph = alnum | punct; }; ``` #### Class `[std::ctype](../locale/ctype "cpp/locale/ctype")` ``` template <class charT> class ctype : public locale::facet, public ctype_base { public: typedef charT char_type; explicit ctype(size_t refs = 0); bool is(mask m, charT c) const; const charT* is(const charT* low, const charT* high, mask* vec) const; const charT* scan_is(mask m, const charT* low, const charT* high) const; const charT* scan_not(mask m, const charT* low, const charT* high) const; charT toupper(charT c) const; const charT* toupper(charT* low, const charT* high) const; charT tolower(charT c) const; const charT* tolower(charT* low, const charT* high) const; charT widen(char c) const; const char* widen(const char* low, const char* high, charT* to) const; char narrow(charT c, char dfault) const; const charT* narrow(const charT* low, const charT*, char dfault, char* to) const; static locale::id id; protected: ~ctype(); virtual bool do_is(mask m, charT c) const; virtual const charT* do_is(const charT* low, const charT* high, mask* vec) const; virtual const charT* do_scan_is(mask m, const charT* low, const charT* high) const; virtual const charT* do_scan_not(mask m, const charT* low, const charT* high) const; virtual charT do_toupper(charT) const; virtual const charT* do_toupper(charT* low, const charT* high) const; virtual charT do_tolower(charT) const; virtual const charT* do_tolower(charT* low, const charT* high) const; virtual charT do_widen(char) const; virtual const char* do_widen(const char* low, const char* high, charT* dest) const; virtual char do_narrow(charT, char dfault) const; virtual const charT* do_narrow(const charT* low, const charT* high, char dfault, char* dest) const; }; ``` #### Class `[std::ctype\_byname](../locale/ctype_byname "cpp/locale/ctype byname")` ``` template <class charT> class ctype_byname : public ctype<charT> { public: typedef typename ctype<charT>::mask mask; explicit ctype_byname(const char*, size_t refs = 0); explicit ctype_byname(const string&, size_t refs = 0); protected: ~ctype_byname(); }; ``` #### Class `[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<char>` ``` template <> class ctype<char> : public locale::facet, public ctype_base { public: typedef char char_type; explicit ctype(const mask* tab = 0, bool del = false, size_t refs = 0); bool is(mask m, char c) const; const char* is(const char* low, const char* high, mask* vec) const; const char* scan_is (mask m, const char* low, const char* high) const; const char* scan_not(mask m, const char* low, const char* high) const; char toupper(char c) const; const char* toupper(char* low, const char* high) const; char tolower(char c) const; const char* tolower(char* low, const char* high) const; char widen(char c) const; const char* widen(const char* low, const char* high, char* to) const; char narrow(char c, char dfault) const; const char* narrow(const char* low, const char* high, char dfault, char* to) const; static locale::id id; static const size_t table_size = implementation-defined; const mask* table() const noexcept; static const mask* classic_table() noexcept; protected: ~ctype(); virtual char do_toupper(char c) const; virtual const char* do_toupper(char* low, const char* high) const; virtual char do_tolower(char c) const; virtual const char* do_tolower(char* low, const char* high) const; virtual char do_widen(char c) const; virtual const char* do_widen(const char* low, const char* high, char* to) const; virtual char do_narrow(char c, char dfault) const; virtual const char* do_narrow(const char* low, const char* high, char dfault, char* to) const; }; ``` #### Class `[std::codecvt\_base](../locale/codecvt_base "cpp/locale/codecvt base")` ``` class codecvt_base { public: enum result { ok, partial, error, noconv }; }; ``` #### Class `[std::codecvt](../locale/codecvt "cpp/locale/codecvt")` ``` template <class internT, class externT, class stateT> class codecvt : public locale::facet, public codecvt_base { public: typedef internT intern_type; typedef externT extern_type; typedef stateT state_type; explicit codecvt(size_t refs = 0); result out(stateT& state, const internT* from, const internT* from_end, const internT*& from_next, externT* to, externT* to_end, externT*& to_next) const; result unshift(stateT& state, externT* to, externT* to_end, externT*& to_next) const; result in(stateT& state, const externT* from, const externT* from_end, const externT*& from_next, internT* to, internT* to_end, internT*& to_next) const; int encoding() const noexcept; bool always_noconv() const noexcept; int length(stateT&, const externT* from, const externT* end, size_t max) const; int max_length() const noexcept; static locale::id id; protected: ~codecvt(); virtual result do_out(stateT& state, const internT* from, const internT* from_end, const internT*& from_next, externT* to, externT* to_end, externT*& to_next) const; virtual result do_in(stateT& state, const externT* from, const externT* from_end, const externT*& from_next, internT* to, internT* to_end, internT*& to_next) const; virtual result do_unshift(stateT& state, externT* to, externT* to_end, externT*& to_next) const; virtual int do_encoding() const noexcept; virtual bool do_always_noconv() const noexcept; virtual int do_length(stateT&, const externT* from, const externT* end, size_t max) const; virtual int do_max_length() const noexcept; }; ``` #### Class `[std::codecvt\_byname](../locale/codecvt_byname "cpp/locale/codecvt byname")` ``` template <class internT, class externT, class stateT> class codecvt_byname : public codecvt<internT, externT, stateT> { public: explicit codecvt_byname(const char*, size_t refs = 0); explicit codecvt_byname(const string&, size_t refs = 0); protected: ~codecvt_byname(); }; ``` #### Class `[std::num\_get](../locale/num_get "cpp/locale/num get")` ``` template <class charT, class InputIterator = istreambuf_iterator<charT>> class num_get : public locale::facet { public: typedef charT char_type; typedef InputIterator iter_type; explicit num_get(size_t refs = 0); iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, bool& v) const; iter_type get(iter_type in, iter_type end, ios_base& , ios_base::iostate& err, long& v) const; iter_type get(iter_type in, iter_type end, ios_base& , ios_base::iostate& err, long long& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, unsigned short& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, unsigned int& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, unsigned long& v) const; iter_type get(iter_type in, iter_type end, ios_base& , ios_base::iostate& err, unsigned long long& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, float& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, double& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, long double& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, void*& v) const; static locale::id id; protected: ~num_get(); virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, bool& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, long& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, long long& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned short& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned int& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned long& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned long long& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, float& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, double& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, long double& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, void*& v) const; }; ``` #### Class `[std::num\_put](../locale/num_put "cpp/locale/num put")` ``` template <class CharT, class OutputIterator = ostreambuf_iterator<CharT>> class num_put : public locale::facet { public: typedef CharT char_type; typedef OutputIterator iter_type; explicit num_put(size_t refs = 0); iter_type put(iter_type s, ios_base& f, char_type fill, bool v) const; iter_type put(iter_type s, ios_base& f, char_type fill, long v) const; iter_type put(iter_type s, ios_base& f, char_type fill, long long v) const; iter_type put(iter_type s, ios_base& f, char_type fill, unsigned long v) const; iter_type put(iter_type s, ios_base& f, char_type fill, unsigned long long v) const; iter_type put(iter_type s, ios_base& f, char_type fill, double v) const; iter_type put(iter_type s, ios_base& f, char_type fill, long double v) const; iter_type put(iter_type s, ios_base& f, char_type fill, const void* v) const; static locale::id id; protected: ~num_put(); virtual iter_type do_put(iter_type, ios_base&, char_type fill, bool v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, long v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, long long v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, unsigned long) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, unsigned long long) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, double v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, long double v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, const void* v) const; }; ``` #### Class `[std::numpunct](../locale/numpunct "cpp/locale/numpunct")` ``` template <class CharT> class numpunct : public locale::facet { public: typedef CharT char_type; typedef basic_string<CharT> string_type; explicit numpunct(size_t refs = 0); char_type decimal_point() const; char_type thousands_sep() const; string grouping() const; string_type truename() const; string_type falsename() const; static locale::id id; protected: ~numpunct(); // virtual virtual char_type do_decimal_point() const; virtual char_type do_thousands_sep() const; virtual string do_grouping() const; virtual string_type do_truename() const; // for bool virtual string_type do_falsename() const; // for bool }; ``` #### Class `[std::numpunct\_byname](../locale/numpunct_byname "cpp/locale/numpunct byname")` ``` template <class CharT> class numpunct_byname : public numpunct<CharT> { public: typedef CharT char_type; typedef basic_string<CharT> string_type; explicit numpunct_byname(const char*, size_t refs = 0); explicit numpunct_byname(const string&, size_t refs = 0); protected: ~numpunct_byname(); }; ``` #### Class `[std::collate](../locale/collate "cpp/locale/collate")` ``` template <class CharT> class collate : public locale::facet { public: typedef CharT char_type; typedef basic_string<CharT> string_type; explicit collate(size_t refs = 0); int compare(const CharT* low1, const CharT* high1, const CharT* low2, const CharT* high2) const; string_type transform(const CharT* low, const CharT* high) const; long hash(const CharT* low, const CharT* high) const; static locale::id id; protected: ~collate(); virtual int do_compare(const CharT* low1, const CharT* high1, const CharT* low2, const CharT* high2) const; virtual string_type do_transform(const CharT* low, const CharT* high) const; virtual long do_hash (const CharT* low, const CharT* high) const; }; ``` #### Class `[std::collate\_byname](../locale/collate_byname "cpp/locale/collate byname")` ``` template <class CharT> class collate_byname : public collate<CharT> { public: typedef basic_string<CharT> string_type; explicit collate_byname(const char*, size_t refs = 0); explicit collate_byname(const string&, size_t refs = 0); protected: ~collate_byname(); }; ``` #### Class `[std::time\_base](../locale/time_base "cpp/locale/time base")` ``` class time_base { public: enum dateorder { no_order, dmy, mdy, ymd, ydm }; }; ``` #### Class `[std::time\_get](../locale/time_get "cpp/locale/time get")` ``` template <class CharT, class InputIterator = istreambuf_iterator<CharT>> class time_get : public locale::facet, public time_base { public: typedef CharT char_type; typedef InputIterator iter_type; explicit time_get(size_t refs = 0); dateorder date_order() const; iter_type get_time(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_date(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_weekday(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_monthname(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_year(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t, char format, char modifier = 0) const; iter_type get(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t, const char_type* fmt, const char_type* fmtend) const; static locale::id id; protected: ~time_get(); virtual dateorder do_date_order() const; virtual iter_type do_get_time(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_date(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_weekday(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_monthname(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_year(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t, char format, char modifier) const; }; ``` #### Class `[std::time\_get\_byname](../locale/time_get_byname "cpp/locale/time get byname")` ``` template <class CharT, class InputIterator = istreambuf_iterator<CharT>> class time_get_byname : public time_get<CharT, InputIterator> { public: typedef time_base::dateorder dateorder; typedef InputIterator iter_type; explicit time_get_byname(const char*, size_t refs = 0); explicit time_get_byname(const string&, size_t refs = 0); protected: ~time_get_byname(); }; ``` #### Class `[std::time\_put](../locale/time_put "cpp/locale/time put")` ``` template <class CharT, class OutputIterator = ostreambuf_iterator<CharT>> class time_put : public locale::facet { public: typedef CharT char_type; typedef OutputIterator iter_type; explicit time_put(size_t refs = 0); // the following is implemented in terms of other member functions. iter_type put(iter_type s, ios_base& f, char_type fill, const tm* tmb, const CharT* pattern, const CharT* pat_end) const; iter_type put(iter_type s, ios_base& f, char_type fill, const tm* tmb, char format, char modifier = 0) const; static locale::id id; protected: ~time_put(); virtual iter_type do_put(iter_type s, ios_base&, char_type, const tm* t, char format, char modifier) const; }; ``` #### Class `[std::time\_put\_byname](../locale/time_put_byname "cpp/locale/time put byname")` ``` template <class CharT, class OutputIterator = ostreambuf_iterator<CharT>> class time_put_byname : public time_put<CharT, OutputIterator> { public: typedef CharT char_type; typedef OutputIterator iter_type; explicit time_put_byname(const char*, size_t refs = 0); explicit time_put_byname(const string&, size_t refs = 0); protected: ~time_put_byname(); }; ``` #### Class `[std::money\_get](../locale/money_get "cpp/locale/money get")` ``` template <class CharT, class InputIterator = istreambuf_iterator<CharT>> class money_get : public locale::facet { public: typedef CharT char_type; typedef InputIterator iter_type; typedef basic_string<CharT> string_type; explicit money_get(size_t refs = 0); iter_type get(iter_type s, iter_type end, bool intl, ios_base& f, ios_base::iostate& err, long double& units) const; iter_type get(iter_type s, iter_type end, bool intl, ios_base& f, ios_base::iostate& err, string_type& digits) const; static locale::id id; protected: ~money_get(); virtual iter_type do_get(iter_type, iter_type, bool, ios_base&, ios_base::iostate& err, long double& units) const; virtual iter_type do_get(iter_type, iter_type, bool, ios_base&, ios_base::iostate& err, string_type& digits) const; }; ``` #### Class `[std::money\_put](../locale/money_put "cpp/locale/money put")` ``` template <class CharT, class OutputIterator = ostreambuf_iterator<CharT>> class money_put : public locale::facet { public: typedef CharT char_type; typedef OutputIterator iter_type; typedef basic_string<CharT> string_type; explicit money_put(size_t refs = 0); iter_type put(iter_type s, bool intl, ios_base& f, char_type fill, long double units) const; iter_type put(iter_type s, bool intl, ios_base& f, char_type fill, const string_type& digits) const; static locale::id id; protected: ~money_put(); virtual iter_type do_put(iter_type, bool, ios_base&, char_type fill, long double units) const; virtual iter_type do_put(iter_type, bool, ios_base&, char_type fill, const string_type& digits) const; }; ``` #### Class `[std::money\_base](../locale/money_base "cpp/locale/money base")` ``` class money_base { public: enum part { none, space, symbol, sign, value }; struct pattern { char field[4]; }; }; ``` #### Class `[std::moneypunct](../locale/moneypunct "cpp/locale/moneypunct")` ``` template <class CharT, bool International = false> class moneypunct : public locale::facet, public money_base { public: typedef CharT char_type; typedef basic_string<CharT> string_type; explicit moneypunct(size_t refs = 0); CharT decimal_point() const; CharT thousands_sep() const; string grouping() const; string_type curr_symbol() const; string_type positive_sign() const; string_type negative_sign() const; int frac_digits() const; pattern pos_format() const; pattern neg_format() const; static locale::id id; static const bool intl = International; protected: ~moneypunct(); virtual CharT do_decimal_point() const; virtual CharT do_thousands_sep() const; virtual string do_grouping() const; virtual string_type do_curr_symbol() const; virtual string_type do_positive_sign() const; virtual string_type do_negative_sign() const; virtual int do_frac_digits() const; virtual pattern do_pos_format() const; virtual pattern do_neg_format() const; }; ``` #### Class `[std::moneypunct\_byname](../locale/moneypunct_byname "cpp/locale/moneypunct byname")` ``` template <class CharT, bool Intl = false> class moneypunct_byname : public moneypunct<CharT, Intl> { public: typedef money_base::pattern pattern; typedef basic_string<CharT> string_type; explicit moneypunct_byname(const char*, size_t refs = 0); explicit moneypunct_byname(const string&, size_t refs = 0); protected: ~moneypunct_byname(); }; ``` #### Class `[std::messages\_base](../locale/messages_base "cpp/locale/messages base")` ``` class messages_base { public: typedef /* unspecified signed integer type */ catalog; }; ``` #### Class `[std::messages](../locale/messages "cpp/locale/messages")` ``` template <class CharT> class messages : public locale::facet, public messages_base { public: typedef CharT char_type; typedef basic_string<CharT> string_type; explicit messages(size_t refs = 0); catalog open(const basic_string<char>& fn, const locale&) const; string_type get(catalog c, int set, int msgid, const string_type& dfault) const; void close(catalog c) const; static locale::id id; protected: ~messages(); virtual catalog do_open(const basic_string<char>&, const locale&) const; virtual string_type do_get(catalog, int set, int msgid, const string_type& dfault) const; virtual void do_close(catalog) const; }; ``` #### Class `[std::messages\_byname](../locale/messages_byname "cpp/locale/messages byname")` ``` template <class CharT> class messages_byname : public messages<CharT> { public: typedef messages_base::catalog catalog; typedef basic_string<CharT> string_type; explicit messages_byname(const char*, size_t refs = 0); explicit messages_byname(const string&, size_t refs = 0); protected: ~messages_byname(); }; ``` #### Class `[std::wstring\_convert](../locale/wstring_convert "cpp/locale/wstring convert")` ``` template<class Codecvt, class Elem = wchar_t, class Wide_alloc = std::allocator<Elem>, class Byte_alloc = std::allocator<char>> class wstring_convert { public: typedef std::basic_string<char, char_traits<char>, Byte_alloc> byte_string; typedef std::basic_string<Elem, char_traits<Elem>, Wide_alloc> wide_string; typedef typename Codecvt::state_type state_type; typedef typename wide_string::traits_type::int_type int_type; explicit wstring_convert(Codecvt* pcvt = new Codecvt); wstring_convert(Codecvt* pcvt, state_type state); explicit wstring_convert(const byte_string& byte_err, const wide_string& wide_err = wide_string()); ~wstring_convert(); wstring_convert(const wstring_convert&) = delete; wstring_convert& operator=(const wstring_convert&) = delete; wide_string from_bytes(char byte); wide_string from_bytes(const char* ptr); wide_string from_bytes(const byte_string& str); wide_string from_bytes(const char* first, const char* last); byte_string to_bytes(Elem wchar); byte_string to_bytes(const Elem* wptr); byte_string to_bytes(const wide_string& wstr); byte_string to_bytes(const Elem* first, const Elem* last); size_t converted() const noexcept; state_type state() const; private: byte_string byte_err_string; // exposition only wide_string wide_err_string; // exposition only Codecvt* cvtptr; // exposition only state_type cvtstate; // exposition only size_t cvtcount; // exposition only }; ``` #### Class `[std::wbuffer\_convert](../locale/wbuffer_convert "cpp/locale/wbuffer convert")` ``` template<class Codecvt, class Elem = wchar_t, class Tr = std::char_traits<Elem>> class wbuffer_convert : public std::basic_streambuf<Elem, Tr> { public: typedef typename Codecvt::state_type state_type; explicit wbuffer_convert(std::streambuf* bytebuf = 0, Codecvt* pcvt = new Codecvt, state_type state = state_type()); ~wbuffer_convert(); wbuffer_convert(const wbuffer_convert&) = delete; wbuffer_convert& operator=(const wbuffer_convert&) = delete; std::streambuf* rdbuf() const; std::streambuf* rdbuf(std::streambuf* bytebuf); state_type state() const; private: std::streambuf* bufptr; // exposition only Codecvt* cvtptr; // exposition only state_type cvtstate; // exposition only }; ``` ### 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 71](https://cplusplus.github.io/LWG/issue71) | C++98 | the parameter `end` of [`time_get::do_get_monthname`](../locale/time_get/get_monthname "cpp/locale/time get/get monthname")was missing in the synopsis | added | | [LWG 75](https://cplusplus.github.io/LWG/issue75) | C++98 | the type of the parameter `state` of members [`length`](../locale/codecvt/length "cpp/locale/codecvt/length") and `do_length`of [`codecvt`](../locale/codecvt "cpp/locale/codecvt") and [`codecvt_byname`](../locale/codecvt_byname "cpp/locale/codecvt byname") was `const stateT&` in the synopsis | changed to `stateT&` |
programming_docs
cpp Standard library header <iterator> Standard library header <iterator> ================================== This header is part of the [iterator](../iterator "cpp/iterator") library. | | | --- | | Concepts | | Iterator concepts | | [indirectly\_readable](../iterator/indirectly_readable "cpp/iterator/indirectly readable") (C++20) | specifies that a type is indirectly readable by applying operator `*` (concept) | | [indirectly\_writable](../iterator/indirectly_writable "cpp/iterator/indirectly writable") (C++20) | specifies that a value can be written to an iterator's referenced object (concept) | | [weakly\_incrementable](../iterator/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) | | [incrementable](../iterator/incrementable "cpp/iterator/incrementable") (C++20) | specifies that the increment operation on a [`weakly_incrementable`](../iterator/weakly_incrementable "cpp/iterator/weakly incrementable") type is equality-preserving and that the type is [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable") (concept) | | [input\_or\_output\_iterator](../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) | | [sentinel\_for](../iterator/sentinel_for "cpp/iterator/sentinel for") (C++20) | specifies a type is a sentinel for an [`input_or_output_iterator`](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator") type (concept) | | [sized\_sentinel\_for](../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") (C++20) | specifies that the `-` operator can be applied to an iterator and a sentinel to calculate their difference in constant time (concept) | | [input\_iterator](../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) | | [output\_iterator](../iterator/output_iterator "cpp/iterator/output iterator") (C++20) | specifies that a type is an output iterator for a given value type, that is, values of that type can be written to it and it can be both pre- and post-incremented (concept) | | [forward\_iterator](../iterator/forward_iterator "cpp/iterator/forward iterator") (C++20) | specifies that an [`input_iterator`](../iterator/input_iterator "cpp/iterator/input iterator") is a forward iterator, supporting equality comparison and multi-pass (concept) | | [bidirectional\_iterator](../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") (C++20) | specifies that a [`forward_iterator`](../iterator/forward_iterator "cpp/iterator/forward iterator") is a bidirectional iterator, supporting movement backwards (concept) | | [random\_access\_iterator](../iterator/random_access_iterator "cpp/iterator/random access iterator") (C++20) | specifies that a [`bidirectional_iterator`](../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") is a random-access iterator, supporting advancement in constant time and subscripting (concept) | | [contiguous\_iterator](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") (C++20) | specifies that a [`random_access_iterator`](../iterator/random_access_iterator "cpp/iterator/random access iterator") is a contiguous iterator, referring to elements that are contiguous in memory (concept) | | Indirect callable concepts | | [indirectly\_unary\_invocableindirectly\_regular\_unary\_invocable](../iterator/indirectly_unary_invocable "cpp/iterator/indirectly unary invocable") (C++20)(C++20) | specifies that a callable type can be invoked with the result of dereferencing an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type (concept) | | [indirect\_unary\_predicate](../iterator/indirect_unary_predicate "cpp/iterator/indirect unary predicate") (C++20) | specifies that a callable type, when invoked with the result of dereferencing an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type, satisfies [`predicate`](../concepts/predicate "cpp/concepts/predicate") (concept) | | [indirect\_binary\_predicate](../iterator/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`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types, satisfies [`predicate`](../concepts/predicate "cpp/concepts/predicate") (concept) | | [indirect\_equivalence\_relation](../iterator/indirect_equivalence_relation "cpp/iterator/indirect equivalence relation") (C++20) | specifies that a callable type, when invoked with the result of dereferencing two [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types, satisfies [`equivalence_relation`](../concepts/equivalence_relation "cpp/concepts/equivalence relation") (concept) | | [indirect\_strict\_weak\_order](../iterator/indirect_strict_weak_order "cpp/iterator/indirect strict weak order") (C++20) | specifies that a callable type, when invoked with the result of dereferencing two [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types, satisfies [`strict_weak_order`](../concepts/strict_weak_order "cpp/concepts/strict weak order") (concept) | | Common algorithm requirements | | [indirectly\_movable](../iterator/indirectly_movable "cpp/iterator/indirectly movable") (C++20) | specifies that values may be moved from an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](../iterator/indirectly_writable "cpp/iterator/indirectly writable") type (concept) | | [indirectly\_movable\_storable](../iterator/indirectly_movable_storable "cpp/iterator/indirectly movable storable") (C++20) | specifies that values may be moved from an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](../iterator/indirectly_writable "cpp/iterator/indirectly writable") type and that the move may be performed via an intermediate object (concept) | | [indirectly\_copyable](../iterator/indirectly_copyable "cpp/iterator/indirectly copyable") (C++20) | specifies that values may be copied from an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](../iterator/indirectly_writable "cpp/iterator/indirectly writable") type (concept) | | [indirectly\_copyable\_storable](../iterator/indirectly_copyable_storable "cpp/iterator/indirectly copyable storable") (C++20) | specifies that values may be copied from an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](../iterator/indirectly_writable "cpp/iterator/indirectly writable") type and that the copy may be performed via an intermediate object (concept) | | [indirectly\_swappable](../iterator/indirectly_swappable "cpp/iterator/indirectly swappable") (C++20) | specifies that the values referenced by two [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types can be swapped (concept) | | [indirectly\_comparable](../iterator/indirectly_comparable "cpp/iterator/indirectly comparable") (C++20) | specifies that the values referenced by two [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types can be compared (concept) | | [permutable](../iterator/permutable "cpp/iterator/permutable") (C++20) | specifies the common requirements of algorithms that reorder elements in place (concept) | | [mergeable](../iterator/mergeable "cpp/iterator/mergeable") (C++20) | specifies the requirements of algorithms that merge sorted sequences into an output sequence by copying elements (concept) | | [sortable](../iterator/sortable "cpp/iterator/sortable") (C++20) | specifies the common requirements of algorithms that permute sequences into ordered sequences (concept) | | Classes | | Algorithm utilities | | [indirect\_result\_t](../iterator/indirect_result_t "cpp/iterator/indirect result t") (C++20) | computes the result of invoking a callable object on the result of dereferencing some set of [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") types (alias template) | | [projected](../iterator/projected "cpp/iterator/projected") (C++20) | helper template for specifying the constraints on algorithms that accept projections (class template) | | Associated types | | [incrementable\_traits](../iterator/incrementable_traits "cpp/iterator/incrementable traits") (C++20) | computes the difference type of a [`weakly_incrementable`](../iterator/weakly_incrementable "cpp/iterator/weakly incrementable") type (class template) | | [indirectly\_readable\_traits](../iterator/indirectly_readable_traits "cpp/iterator/indirectly readable traits") (C++20) | computes the value type of an [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") type (class template) | | [iter\_value\_titer\_reference\_titer\_const\_reference\_titer\_difference\_titer\_rvalue\_reference\_titer\_common\_reference\_t](../iterator/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) | | Primitives | | [iterator\_traits](../iterator/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/iterator_tags "cpp/iterator/iterator tags") (C++20) | empty class types used to indicate iterator categories (class) | | [iterator](../iterator/iterator "cpp/iterator/iterator") (deprecated in C++17) | base class to ease the definition of required types for simple iterators (class template) | | Adaptors | | [reverse\_iterator](../iterator/reverse_iterator "cpp/iterator/reverse iterator") | iterator adaptor for reverse-order traversal (class template) | | [move\_iterator](../iterator/move_iterator "cpp/iterator/move iterator") (C++11) | iterator adaptor which dereferences to an rvalue reference (class template) | | [move\_sentinel](../iterator/move_sentinel "cpp/iterator/move sentinel") (C++20) | sentinel adaptor for use with `[std::move\_iterator](../iterator/move_iterator "cpp/iterator/move iterator")` (class template) | | [common\_iterator](../iterator/common_iterator "cpp/iterator/common iterator") (C++20) | adapts an iterator type and its sentinel into a common iterator type (class template) | | [default\_sentinel\_t](../iterator/default_sentinel_t "cpp/iterator/default sentinel t") (C++20) | default sentinel for use with iterators that know the bound of their range (class) | | [counted\_iterator](../iterator/counted_iterator "cpp/iterator/counted iterator") (C++20) | iterator adaptor that tracks the distance to the end of the range (class template) | | [unreachable\_sentinel\_t](../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t") (C++20) | sentinel that always compares unequal to any [`weakly_incrementable`](../iterator/weakly_incrementable "cpp/iterator/weakly incrementable") type (class) | | [back\_insert\_iterator](../iterator/back_insert_iterator "cpp/iterator/back insert iterator") | iterator adaptor for insertion at the end of a container (class template) | | [front\_insert\_iterator](../iterator/front_insert_iterator "cpp/iterator/front insert iterator") | iterator adaptor for insertion at the front of a container (class template) | | [insert\_iterator](../iterator/insert_iterator "cpp/iterator/insert iterator") | iterator adaptor for insertion into a container (class template) | | Stream Iterators | | [istream\_iterator](../iterator/istream_iterator "cpp/iterator/istream iterator") | input iterator that reads from `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` (class template) | | [ostream\_iterator](../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](../iterator/istreambuf_iterator "cpp/iterator/istreambuf iterator") | input iterator that reads from `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) | | [ostreambuf\_iterator](../iterator/ostreambuf_iterator "cpp/iterator/ostreambuf iterator") | output iterator that writes to `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) | | Customization point objects | | Defined in namespace `std::ranges` | | [iter\_move](../iterator/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](../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap") (C++20) | swaps the values referenced by two dereferenceable objects (customization point object) | | Constants | | [unreachable\_sentinel](../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t") (C++20) | an object of type `unreachable_sentinel_t` that always compares unequal to any [`weakly_incrementable`](../iterator/weakly_incrementable "cpp/iterator/weakly incrementable") type (constant) | | [default\_sentinel](../iterator/default_sentinel_t "cpp/iterator/default sentinel t") (C++20) | an object of type `default_sentinel_t` used with iterators that know the bound of their range (constant) | | Functions | | Adaptors | | [make\_reverse\_iterator](../iterator/make_reverse_iterator "cpp/iterator/make reverse iterator") (C++14) | creates a `[std::reverse\_iterator](../iterator/reverse_iterator "cpp/iterator/reverse iterator")` of type inferred from the argument (function template) | | [make\_move\_iterator](../iterator/make_move_iterator "cpp/iterator/make move iterator") (C++11) | creates a `[std::move\_iterator](../iterator/move_iterator "cpp/iterator/move iterator")` of type inferred from the argument (function template) | | [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) | | [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) | | [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) | | Non-member operators | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../iterator/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+](../iterator/move_iterator/operator_plus_ "cpp/iterator/move iterator/operator+") (C++11) | advances the iterator (function template) | | [operator-](../iterator/move_iterator/operator- "cpp/iterator/move iterator/operator-") (C++11) | computes the distance between two iterator adaptors (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../iterator/reverse_iterator/operator_cmp "cpp/iterator/reverse iterator/operator cmp") (C++20) | compares the underlying iterators (function template) | | [operator+](../iterator/reverse_iterator/operator_plus_ "cpp/iterator/reverse iterator/operator+") | advances the iterator (function template) | | [operator-](../iterator/reverse_iterator/operator- "cpp/iterator/reverse iterator/operator-") | computes the distance between two iterator adaptors (function template) | | [operator==operator<=>](../iterator/counted_iterator/operator_cmp "cpp/iterator/counted iterator/operator cmp") (C++20) | compares the distances to the end (function template) | | [operator+](../iterator/counted_iterator/operator_plus_ "cpp/iterator/counted iterator/operator+") (C++20) | advances the iterator (function template) | | [operator-](../iterator/counted_iterator/operator- "cpp/iterator/counted iterator/operator-") (C++20) | computes the distance between two iterator adaptors (function template) | | [operator==operator!=](../iterator/istream_iterator/operator_cmp "cpp/iterator/istream iterator/operator cmp") (removed in C++20) | compares two `istream_iterator`s (function template) | | [operator==operator!=](../iterator/istreambuf_iterator/operator_cmp "cpp/iterator/istreambuf iterator/operator cmp") (removed in C++20) | compares two `istreambuf_iterator`s (function template) | | Operations | | [advance](../iterator/advance "cpp/iterator/advance") | advances an iterator by given distance (function template) | | [distance](../iterator/distance "cpp/iterator/distance") | returns the distance between two iterators (function template) | | [next](../iterator/next "cpp/iterator/next") (C++11) | increment an iterator (function template) | | [prev](../iterator/prev "cpp/iterator/prev") (C++11) | decrement an iterator (function template) | | [ranges::advance](../iterator/ranges/advance "cpp/iterator/ranges/advance") (C++20) | advances an iterator by given distance or to a given bound (niebloid) | | [ranges::distance](../iterator/ranges/distance "cpp/iterator/ranges/distance") (C++20) | returns the distance between an iterator and a sentinel, or between the beginning and end of a range (niebloid) | | [ranges::next](../iterator/ranges/next "cpp/iterator/ranges/next") (C++20) | increment an iterator by a given distance or to a bound (niebloid) | | [ranges::prev](../iterator/ranges/prev "cpp/iterator/ranges/prev") (C++20) | decrement an iterator by a given distance or to a bound (niebloid) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <concepts> namespace std { template<class T> using /*with-reference*/ = T&; // exposition only template<class T> concept /*can-reference*/ // exposition only = requires { typename /*with-reference*/<T>; }; template<class T> concept /*dereferenceable*/ // exposition only = requires(T& t) { { *t } -> /*can-reference*/; // not required to be equality-preserving }; // associated types // incrementable traits template<class> struct incrementable_traits; template<class T> using iter_difference_t = /* see description */; // indirectly readable traits template<class> struct indirectly_readable_traits; template<class T> using iter_value_t = /* see description */; // iterator traits template<class I> struct iterator_traits; template<class T> requires is_object_v<T> struct iterator_traits<T*>; template</*dereferenceable*/ T> using iter_reference_t = decltype(*declval<T&>()); namespace ranges { // customization point objects inline namespace /* unspecified */ { // ranges::iter_move inline constexpr /* unspecified */ iter_move = /* unspecified */; // ranges::iter_swap inline constexpr /* unspecified */ iter_swap = /* unspecified */; } } template</*dereferenceable*/ T> requires requires(T& t) { { ranges::iter_move(t) } -> /*can-reference*/; } using iter_rvalue_reference_t = decltype(ranges::iter_move(declval<T&>())); // iterator concepts // concept indirectly_readable template<class In> concept indirectly_readable = /* see description */; template<indirectly_readable T> using iter_common_reference_t = common_reference_t<iter_reference_t<T>, iter_value_t<T>&>; // concept indirectly_writable template<class Out, class T> concept indirectly_writable = /* see description */; // concept weakly_incrementable template<class I> concept weakly_incrementable = /* see description */; // concept incrementable template<class I> concept incrementable = /* see description */; // concept input_or_output_iterator template<class I> concept input_or_output_iterator = /* see description */; // concept sentinel_for template<class S, class I> concept sentinel_for = /* see description */; // concept sized_sentinel_for template<class S, class I> inline constexpr bool disable_sized_sentinel_for = false; template<class S, class I> concept sized_sentinel_for = /* see description */; // concept input_iterator template<class I> concept input_iterator = /* see description */; // concept output_iterator template<class I, class T> concept output_iterator = /* see description */; // concept forward_iterator template<class I> concept forward_iterator = /* see description */; // concept bidirectional_iterator template<class I> concept bidirectional_iterator = /* see description */; // concept random_access_iterator template<class I> concept random_access_iterator = /* see description */; // concept contiguous_iterator template<class I> concept contiguous_iterator = /* see description */; // indirect callable requirements // indirect callables template<class F, class I> concept indirectly_unary_invocable = /* see description */; template<class F, class I> concept indirectly_regular_unary_invocable = /* see description */; template<class F, class I> concept indirect_unary_predicate = /* see description */; template<class F, class I1, class I2> concept indirect_binary_predicate = /* see description */; template<class F, class I1, class I2 = I1> concept indirect_equivalence_relation = /* see description */; template<class F, class I1, class I2 = I1> concept indirect_strict_weak_order = /* see description */; template<class F, class... Is> requires (indirectly_readable<Is> && ...) && invocable<F, iter_reference_t<Is>...> using indirect_result_t = invoke_result_t<F, iter_reference_t<Is>...>; // projected template<indirectly_readable I, indirectly_regular_unary_invocable<I> Proj> struct projected; template<weakly_incrementable I, class Proj> struct incrementable_traits<projected<I, Proj>>; // common algorithm requirements // concept indirectly_movable template<class In, class Out> concept indirectly_movable = /* see description */; template<class In, class Out> concept indirectly_movable_storable = /* see description */; // concept indirectly_copyable template<class In, class Out> concept indirectly_copyable = /* see description */; template<class In, class Out> concept indirectly_copyable_storable = /* see description */; // concept indirectly_swappable template<class I1, class I2 = I1> concept indirectly_swappable = /* see description */; // concept indirectly_comparable template<class I1, class I2, class R, class P1 = identity, class P2 = identity> concept indirectly_comparable = /* see description */; // concept permutable template<class I> concept permutable = /* see description */; // concept mergeable template<class I1, class I2, class Out, class R = ranges::less, class P1 = identity, class P2 = identity> concept mergeable = /* see description */; // concept sortable template<class I, class R = ranges::less, class P = identity> concept sortable = /* see description */; // primitives // iterator tags struct input_iterator_tag { }; struct output_iterator_tag { }; struct forward_iterator_tag: public input_iterator_tag { }; struct bidirectional_iterator_tag: public forward_iterator_tag { }; struct random_access_iterator_tag: public bidirectional_iterator_tag { }; struct contiguous_iterator_tag: public random_access_iterator_tag { }; // iterator operations template<class InputIt, class Distance> constexpr void advance(InputIt& i, Distance n); template<class InputIt> constexpr typename iterator_traits<InputIt>::difference_type distance(InputIt first, InputIt last); template<class InputIt> constexpr InputIt next(InputIt x, typename iterator_traits<InputIt>::difference_type n = 1); template<class BidirIt> constexpr BidirIt prev(BidirIt x, ypename iterator_traits<BidirIt>::difference_type n = 1); // range iterator operations namespace ranges { // ranges::advance template<input_or_output_iterator I> constexpr void advance(I& i, iter_difference_t<I> n); template<input_or_output_iterator I, sentinel_for<I> S> constexpr void advance(I& i, S bound); template<input_or_output_iterator I, sentinel_for<I> S> constexpr iter_difference_t<I> advance(I& i, iter_difference_t<I> n, S bound); // ranges::distance template<input_or_output_iterator I, sentinel_for<I> S> constexpr iter_difference_t<I> distance(I first, S last); template<range R> constexpr range_difference_t<R> distance(R&& r); // ranges::next template<input_or_output_iterator I> constexpr I next(I x); template<input_or_output_iterator I> constexpr I next(I x, iter_difference_t<I> n); template<input_or_output_iterator I, sentinel_for<I> S> constexpr I next(I x, S bound); template<input_or_output_iterator I, sentinel_for<I> S> constexpr I next(I x, iter_difference_t<I> n, S bound); // ranges::prev template<bidirectional_iterator I> constexpr I prev(I x); template<bidirectional_iterator I> constexpr I prev(I x, iter_difference_t<I> n); template<bidirectional_iterator I> constexpr I prev(I x, iter_difference_t<I> n, I bound); } // predefined iterators and sentinels // reverse iterators template<class It> class reverse_iterator; template<class It1, class It2> constexpr bool operator==(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, class It2> constexpr bool operator!=(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, class It2> constexpr bool operator<(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, class It2> constexpr bool operator>(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, class It2> constexpr bool operator<=(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, class It2> constexpr bool operator>=(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, three_way_comparable_with<It1> It2> constexpr compare_three_way_result_t<It1, It2> operator<=>(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y); template<class It1, class It2> constexpr auto operator-(const reverse_iterator<It1>& x, const reverse_iterator<It2>& y) -> decltype(y.base() - x.base()); template<class It> constexpr reverse_iterator<It> operator+(iter_difference_t<It> n, const reverse_iterator<It>& x); template<class It> constexpr reverse_iterator<It> make_reverse_iterator(It i); template<class It1, class It2> requires (!sized_sentinel_for<It1, It2>) inline constexpr bool disable_sized_sentinel_for<reverse_iterator<It1>, reverse_iterator<It2>> = true; // insert iterators template<class Container> class back_insert_iterator; template<class Container> constexpr back_insert_iterator<Container> back_inserter(Container& x); template<class Container> class front_insert_iterator; template<class Container> constexpr front_insert_iterator<Container> front_inserter(Container& x); template<class Container> class insert_iterator; template<class Container> constexpr insert_iterator<Container> inserter(Container& x, ranges::iterator_t<Container> i); // move iterators and sentinels template<class It> class move_iterator; template<class It1, class It2> constexpr bool operator==(const move_iterator<It1>& x, const move_iterator<It2>& y); template<class It1, class It2> constexpr bool operator<(const move_iterator<It1>& x, const move_iterator<It2>& y); template<class It1, class It2> constexpr bool operator>(const move_iterator<It1>& x, const move_iterator<It2>& y); template<class It1, class It2> constexpr bool operator<=(const move_iterator<It1>& x, const move_iterator<It2>& y); template<class It1, class It2> constexpr bool operator>=(const move_iterator<It1>& x, const move_iterator<It2>& y); template<class It1, three_way_comparable_with<It1> It2> constexpr compare_three_way_result_t<It1, It2> operator<=>(const move_iterator<It1>& x, const move_iterator<It2>& y); template<class It1, class It2> constexpr auto operator-(const move_iterator<It1>& x, const move_iterator<It2>& y) -> decltype(x.base() - y.base()); template<class It> constexpr move_iterator<It> operator+(iter_difference_t<It> n, const move_iterator<It>& x); template<class It> constexpr move_iterator<It> make_move_iterator(It i); template<semiregular S> class move_sentinel; // common iterators template<input_or_output_iterator I, sentinel_for<I> S> requires (!same_as<I, S> && copyable<I>) class common_iterator; template<class I, class S> struct incrementable_traits<common_iterator<I, S>>; template<input_iterator I, class S> struct iterator_traits<common_iterator<I, S>>; // default sentinel struct default_sentinel_t; inline constexpr default_sentinel_t default_sentinel{}; // counted iterators template<input_or_output_iterator I> class counted_iterator; template<input_iterator I> requires /* see description */ struct iterator_traits<counted_iterator<I>>; // unreachable sentinel struct unreachable_sentinel_t; inline constexpr unreachable_sentinel_t unreachable_sentinel{}; // stream iterators template<class T, class CharT = char, class Traits = char_traits<CharT>, class Distance = ptrdiff_t> class istream_iterator; template<class T, class CharT, class Traits, class Distance> bool operator==(const istream_iterator<T, CharT, Traits, Distance>& x, const istream_iterator<T, CharT, Traits, Distance>& y); template<class T, class CharT = char, class traits = char_traits<CharT>> class ostream_iterator; template<class CharT, class Traits = char_traits<CharT>> class istreambuf_iterator; template<class CharT, class Traits> bool operator==(const istreambuf_iterator<CharT, Traits>& a, const istreambuf_iterator<CharT, Traits>& b); template<class CharT, class Traits = char_traits<CharT>> class ostreambuf_iterator; // range access template<class C> constexpr auto begin(C& c) -> decltype(c.begin()); template<class C> constexpr auto begin(const C& c) -> decltype(c.begin()); template<class C> constexpr auto end(C& c) -> decltype(c.end()); template<class C> constexpr auto end(const C& c) -> decltype(c.end()); template<class T, size_t N> constexpr T* begin(T (&a)[N]) noexcept; template<class T, size_t N> constexpr T* end(T (&a)[N]) noexcept; template<class C> constexpr auto cbegin(const C& c) noexcept(noexcept(std::begin(c))) -> decltype(std::begin(c)); template<class C> constexpr auto cend(const C& c) noexcept(noexcept(std::end(c))) -> decltype(std::end(c)); template<class C> constexpr auto rbegin(C& c) -> decltype(c.rbegin()); template<class C> constexpr auto rbegin(const C& c) -> decltype(c.rbegin()); template<class C> constexpr auto rend(C& c) -> decltype(c.rend()); template<class C> constexpr auto rend(const C& c) -> decltype(c.rend()); template<class T, size_t N> constexpr reverse_iterator<T*> rbegin(T (&a)[N]); template<class T, size_t N> constexpr reverse_iterator<T*> rend(T (&a)[N]); template<class E> constexpr reverse_iterator<const E*> rbegin(initializer_list<E> il); template<class E> constexpr reverse_iterator<const E*> rend(initializer_list<E> il); template<class C> constexpr auto crbegin(const C& c) -> decltype(std::rbegin(c)); template<class C> constexpr auto crend(const C& c) -> decltype(std::rend(c)); template<class C> constexpr auto size(const C& c) -> decltype(c.size()); template<class T, size_t N> constexpr size_t size(const T (&a)[N]) noexcept; template<class C> constexpr auto ssize(const C& c) -> common_type_t<ptrdiff_t, make_signed_t<decltype(c.size())>>; template<class T, ptrdiff_t N> constexpr ptrdiff_t ssize(const T (&a)[N]) noexcept; template<class C> [[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty()); template<class T, size_t N> [[nodiscard]] constexpr bool empty(const T (&a)[N]) noexcept; template<class E> [[nodiscard]] constexpr bool empty(initializer_list<E> il) noexcept; template<class C> constexpr auto data(C& c) -> decltype(c.data()); template<class C> constexpr auto data(const C& c) -> decltype(c.data()); template<class T, size_t N> constexpr T* data(T (&a)[N]) noexcept; template<class E> constexpr const E* data(initializer_list<E> il) noexcept; } ``` #### Concept [`indirectly_readable`](../iterator/indirectly_readable "cpp/iterator/indirectly readable") ``` namespace std { template<class In> concept __indirectlyReadableImpl = // exposition only requires(const In in) { typename iter_value_t<In>; typename iter_reference_t<In>; typename iter_rvalue_reference_t<In>; { *in } -> same_as<iter_reference_t<In>> { iter_move(in) } -> same_as<iter_rvalue_reference_t<In>> } && common_reference_with<iter_reference_t<In>&&, iter_value_t<In>&> && common_reference_with<iter_reference_t<In>&&, iter_rvalue_reference_t<In>&&> && common_reference_with<iter_rvalue_reference_t<In>&&, const iter_value_t<In>&>; template<class In> concept indirectly_readable = __indirectlyReadableImpl<remove_cvref_t<In>> } ``` #### Concept [`indirectly_writable`](../iterator/indirectly_writable "cpp/iterator/indirectly writable") ``` namespace std { template<class Out, class T> concept indirectly_writable = requires(Out&& o, T&& t) { *o = std::forward<T>(t); // not required to be equality-preserving *std::forward<Out>(o) = std::forward<T>(t); // not required to be equality-preserving const_cast<const iter_reference_t<Out>&&>(*o) = std::forward<T>(t); // not required to be equality-preserving const_cast<const iter_reference_t<Out>&&>(*std::forward<Out>(o)) = std::forward<T>(t); // not required to be equality-preserving }; } ``` #### Concept [`weakly_incrementable`](../iterator/weakly_incrementable "cpp/iterator/weakly incrementable") ``` namespace std { template<class T> inline constexpr bool __is_integer_like = /* see description */; // exposition only template<class T> inline constexpr bool __is_signed_integer_like = // exposition only /* see description */; template<class I> concept weakly_incrementable = default_initializable<I> && movable<I> && requires(I i) { typename iter_difference_t<I>; requires __is_signed_integer_like<iter_difference_t<I>>; { ++i } -> same_as<I&>; // not required to be equality-preserving i++; // not required to be equality-preserving }; } ``` #### Concept [`incrementable`](../iterator/incrementable "cpp/iterator/incrementable") ``` namespace std { template<class I> concept incrementable = regular<I> && weakly_incrementable<I> && requires(I i) { { i++ } -> same_as<I>; }; } ``` #### Concept [`input_or_output_iterator`](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator") ``` namespace std { template<class I> concept input_or_output_iterator = requires(I i) { { *i } -> can-reference; } && weakly_incrementable<I>; } ``` #### Concept [`sentinel_for`](../iterator/sentinel_for "cpp/iterator/sentinel for") ``` namespace std { template<class S, class I> concept sentinel_for = semiregular<S> && input_or_output_iterator<I> && __WeaklyEqualityComparableWith<S, I>; } ``` #### Concept [`sized_sentinel_for`](../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") ``` namespace std { template<class S, class I> concept sized_sentinel_for = sentinel_for<S, I> && !disable_sized_sentinel<remove_cv_t<S>, remove_cv_t<I>> && requires(const I& i, const S& s) { { s - i } -> same_as<iter_difference_t<I>>; { i - s } -> same_as<iter_difference_t<I>>; }; } ``` #### Concept [`input_iterator`](../iterator/input_iterator "cpp/iterator/input iterator") ``` namespace std { template<class I> concept input_iterator = input_or_output_iterator<I> && indirectly_readable<I> && requires { typename /*ITER_CONCEPT*/(I); } && derived_from</*ITER_CONCEPT*/(I), input_iterator_tag>; } ``` #### Concept [`output_iterator`](../iterator/output_iterator "cpp/iterator/output iterator") ``` namespace std { template<class I, class T> concept output_iterator = input_or_output_iterator<I> && indirectly_writable<I, T> && requires(I i, T&& t) { *i++ = std::forward<T>(t); // not required to be equality-preserving }; } ``` #### Concept [`forward_iterator`](../iterator/forward_iterator "cpp/iterator/forward iterator") ``` namespace std { template<class I> concept forward_iterator = input_iterator<I> && derived_from</*ITER_CONCEPT*/(I), forward_iterator_tag> && incrementable<I> && sentinel_for<I, I>; } ``` #### Concept [`bidirectional_iterator`](../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") ``` namespace std { template<class I> concept bidirectional_iterator = forward_iterator<I> && derived_from</*ITER_CONCEPT*/(I), bidirectional_iterator_tag> && requires(I i) { { --i } -> same_as<I&>; { i-- } -> same_as<I>; }; } ``` #### Concept [`random_access_iterator`](../iterator/random_access_iterator "cpp/iterator/random access iterator") ``` namespace std { template<class I> concept random_access_iterator = bidirectional_iterator<I> && derived_from</*ITER_CONCEPT*/(I), random_access_iterator_tag> && totally_ordered<I> && sized_sentinel_for<I, I> && requires(I i, const I j, const iter_difference_t<I> n) { { i += n } -> same_as<I&>; { j + n } -> same_as<I>; { n + j } -> same_as<I>; { i -= n } -> same_as<I&>; { j - n } -> same_as<I>; { j[n] } -> same_as<iter_reference_t<I>>; }; } ``` #### Concept [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") ``` namespace std { template<class I> concept contiguous_iterator = random_access_iterator<I> && derived_from</*ITER_CONCEPT*/(I), contiguous_iterator_tag> && is_lvalue_reference_v<iter_reference_t<I>> && same_as<iter_value_t<I>, remove_cvref_t<iter_reference_t<I>>> && requires(const I& i) { { to_address(i) } -> same_as<add_pointer_t<iter_reference_t<I>>>; }; } ``` #### Concept [`indirectly_unary_invocable`](../iterator/indirectly_unary_invocable "cpp/iterator/indirectly unary invocable") ``` namespace std { template<class F, class I> concept indirectly_unary_invocable = indirectly_readable<I> && copy_constructible<F> && invocable<F&, iter_value_t<I>&> && invocable<F&, iter_reference_t<I>> && invocable<F&, iter_common_reference_t<I>> && common_reference_with< invoke_result_t<F&, iter_value_t<I>&>, invoke_result_t<F&, iter_reference_t<I>>>; } ``` #### Concept [`indirectly_regular_unary_invocable`](../iterator/indirectly_unary_invocable "cpp/iterator/indirectly unary invocable") ``` namespace std { template<class F, class I> concept indirectly_regular_unary_invocable = indirectly_readable<I> && copy_constructible<F> && regular_invocable<F&, iter_value_t<I>&> && regular_invocable<F&, iter_reference_t<I>> && regular_invocable<F&, iter_common_reference_t<I>> && common_reference_with< invoke_result_t<F&, iter_value_t<I>&>, invoke_result_t<F&, iter_reference_t<I>>>; } ``` #### Concept [`indirect_unary_predicate`](../iterator/indirect_unary_predicate "cpp/iterator/indirect unary predicate") ``` namespace std { template<class F, class I> concept indirect_unary_predicate = indirectly_readable<I> && copy_constructible<F> && predicate<F&, iter_value_t<I>&> && predicate<F&, iter_reference_t<I>> && predicate<F&, iter_common_reference_t<I>>; } ``` #### Concept [`indirect_binary_predicate`](../iterator/indirect_binary_predicate "cpp/iterator/indirect binary predicate") ``` namespace std { template<class F, class I1, class I2 = I1> concept indirect_binary_predicate = indirectly_readable<I1> && indirectly_readable<I2> && copy_constructible<F> && predicate<F&, iter_value_t<I1>&, iter_value_t<I2>&> && predicate<F&, iter_value_t<I1>&, iter_reference_t<I2>> && predicate<F&, iter_reference_t<I1>, iter_value_t<I2>&> && predicate<F&, iter_reference_t<I1>, iter_reference_t<I2>> && predicate<F&, iter_common_reference_t<I1>, iter_common_reference_t<I2>>; } ``` #### Concept [`indirect_equivalence_relation`](../iterator/indirect_equivalence_relation "cpp/iterator/indirect equivalence relation") ``` namespace std { template<class F, class I1, class I2 = I1> concept indirect_equivalence_relation = indirectly_readable<I1> && indirectly_readable<I2> && copy_constructible<F> && equivalence_relation<F&, iter_value_t<I1>&, iter_value_t<I2>&> && equivalence_relation<F&, iter_value_t<I1>&, iter_reference_t<I2>> && equivalence_relation<F&, iter_reference_t<I1>, iter_value_t<I2>&> && equivalence_relation<F&, iter_reference_t<I1>, iter_reference_t<I2>> && equivalence_relation<F&, iter_common_reference_t<I1>, iter_common_reference_t<I2>>; } ``` #### Concept [`indirect_strict_weak_order`](../iterator/indirect_strict_weak_order "cpp/iterator/indirect strict weak order") ``` namespace std { template<class F, class I1, class I2 = I1> concept indirect_strict_weak_order = indirectly_readable<I1> && indirectly_readable<I2> && copy_constructible<F> && strict_weak_order<F&, iter_value_t<I1>&, iter_value_t<I2>&> && strict_weak_order<F&, iter_value_t<I1>&, iter_reference_t<I2>> && strict_weak_order<F&, iter_reference_t<I1>, iter_value_t<I2>&> && strict_weak_order<F&, iter_reference_t<I1>, iter_reference_t<I2>> && strict_weak_order<F&, iter_common_reference_t<I1>, iter_common_reference_t<I2>>; } ``` #### Concept [`indirectly_movable`](../iterator/indirectly_movable "cpp/iterator/indirectly movable") ``` namespace std { template<class In, class Out> concept indirectly_movable = indirectly_readable<In> && indirectly_writable<Out, iter_rvalue_reference_t<In>>; } ``` #### Concept [`indirectly_movable_storable`](../iterator/indirectly_movable_storable "cpp/iterator/indirectly movable storable") ``` namespace std { template<class In, class Out> concept indirectly_movable_storable = indirectly_movable<In, Out> && indirectly_writable<Out, iter_value_t<In>> && movable<iter_value_t<In>> && constructible_from<iter_value_t<In>, iter_rvalue_reference_t<In>> && assignable_from<iter_value_t<In>&, iter_rvalue_reference_t<In>>; } ``` #### Concept [`indirectly_copyable`](../iterator/indirectly_copyable "cpp/iterator/indirectly copyable") ``` namespace std { template<class In, class Out> concept indirectly_copyable = indirectly_readable<In> && indirectly_writable<Out, iter_reference_t<In>>; } ``` #### Concept [`indirectly_copyable_storable`](../iterator/indirectly_copyable_storable "cpp/iterator/indirectly copyable storable") ``` namespace std { template<class In, class Out> concept indirectly_copyable_storable = indirectly_copyable<In, Out> && indirectly_writable<Out, iter_value_t<In>&> && indirectly_writable<Out, const iter_value_t<In>&> && indirectly_writable<Out, iter_value_t<In>&&> && indirectly_writable<Out, const iter_value_t<In>&&> && copyable<iter_value_t<In>> && constructible_from<iter_value_t<In>, iter_reference_t<In>> && assignable_from<iter_value_t<In>&, iter_reference_t<In>>; } ``` #### Concept [`indirectly_swappable`](../iterator/indirectly_swappable "cpp/iterator/indirectly swappable") ``` namespace std { template<class I1, class I2 = I1> concept indirectly_swappable = indirectly_readable<I1> && indirectly_readable<I2> && requires(const I1 i1, const I2 i2) { ranges::iter_swap(i1, i1); ranges::iter_swap(i2, i2); ranges::iter_swap(i1, i2); ranges::iter_swap(i2, i1); }; } ``` #### Concept [`indirectly_comparable`](../iterator/indirectly_comparable "cpp/iterator/indirectly comparable") ``` namespace std { template<class I1, class I2, class R, class P1 = identity, class P2 = identity> concept indirectly_comparable = indirect_predicate<R, projected<I1, P1>, projected<I2, P2>>; } ``` #### Concept [`permutable`](../iterator/permutable "cpp/iterator/permutable") ``` namespace std { template<class I> concept permutable = forward_iterator<I> && indirectly_movable_storable<I, I> && indirectly_swappable<I, I>; } ``` #### Concept [`mergeable`](../iterator/mergeable "cpp/iterator/mergeable") ``` namespace std { template<class I1, class I2, class Out, class R = ranges::less, class P1 = identity, class P2 = identity> concept mergeable = input_iterator<I1> && input_iterator<I2> && weakly_incrementable<Out> && indirectly_copyable<I1, Out> && indirectly_copyable<I2, Out> && indirect_strict_weak_order<R, projected<I1, P1>, projected<I2, P2>>; } ``` #### Concept [`sortable`](../iterator/sortable "cpp/iterator/sortable") ``` namespace std { template<class I, class R = ranges::less, class P = identity> concept sortable = permutable<I> && indirect_strict_weak_order<R, projected<I, P>>; } ``` #### Class template `[std::incrementable\_traits](../iterator/incrementable_traits "cpp/iterator/incrementable traits")` ``` namespace std { template<class> struct incrementable_traits { }; template<class T> requires is_object_v<T> struct incrementable_traits<T*> { using difference_type = ptrdiff_t; }; template<class I> struct incrementable_traits<const I> : incrementable_traits<I> { }; template<class T> requires requires { typename T::difference_type; } struct incrementable_traits<T> { using difference_type = typename T::difference_type; }; template<class T> requires (!requires { typename T::difference_type; } && requires(const T& a, const T& b) { { a - b } -> integral; }) struct incrementable_traits<T> { using difference_type = make_signed_t<decltype(declval<T>() - declval<T>())>; }; template<class T> using iter_difference_t = /* see description */; } ``` #### Class template `[std::indirectly\_readable\_traits](../iterator/indirectly_readable_traits "cpp/iterator/indirectly readable traits")` ``` namespace std { template<class> struct __cond_value_type { }; // exposition only template<class T> requires is_object_v<T> struct __cond_value_type { using value_type = remove_cv_t<T>; }; template<class> struct indirectly_readable_traits { }; template<class T> struct indirectly_readable_traits<T*> : __cond_value_type<T> { }; template<class I> requires is_array_v<I> struct indirectly_readable_traits<I> { using value_type = remove_cv_t<remove_extent_t<I>>; }; template<class I> struct indirectly_readable_traits<const I> : indirectly_readable_traits<I> { }; template<class T> requires requires { typename T::value_type; } struct indirectly_readable_traits<T> : __cond_value_type<typename T::value_type> { }; template<class T> requires requires { typename T::element_type; } struct indirectly_readable_traits<T> : __cond_value_type<typename T::element_type> { }; } ``` #### Class template `[std::projected](../iterator/projected "cpp/iterator/projected")` ``` namespace std { template<indirectly_readable I, indirectly_regular_unary_invocable<I> Proj> struct projected { using value_type = remove_cvref_t<indirect_result_t<Proj&, I>>; indirect_result_t<Proj&, I> operator*() const; // not defined }; template<weakly_incrementable I, class Proj> struct incrementable_traits<projected<I, Proj>> { using difference_type = iter_difference_t<I>; }; } ``` #### Class template `[std::iterator\_traits](../iterator/iterator_traits "cpp/iterator/iterator traits")` ``` namespace std { template<class I> struct iterator_traits { using iterator_category = /* see description */; using value_type = /* see description */; using difference_type = /* see description */; using pointer = /* see description */; using reference = /* see description */; }; template<class T> requires is_object_v<T> struct iterator_traits<T*> { using iterator_concept = contiguous_iterator_tag; using iterator_category = random_access_iterator_tag; using value_type = remove_cv_t<T>; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } ``` #### Iterator tags ``` namespace std { struct input_iterator_tag { }; struct output_iterator_tag { }; struct forward_iterator_tag: public input_iterator_tag { }; struct bidirectional_iterator_tag: public forward_iterator_tag { }; struct random_access_iterator_tag: public bidirectional_iterator_tag { }; struct contiguous_iterator_tag: public random_access_iterator_tag { }; } ``` #### Class template `[std::reverse\_iterator](../iterator/reverse_iterator "cpp/iterator/reverse iterator")` ``` namespace std { template<class Iter> class reverse_iterator { public: using iterator_type = Iter; using iterator_concept = /* see description */; using iterator_category = /* see description */; using value_type = iter_value_t<Iter>; using difference_type = iter_difference_t<Iter>; using pointer = typename iterator_traits<Iter>::pointer; using reference = iter_reference_t<Iter>; constexpr reverse_iterator(); constexpr explicit reverse_iterator(Iter x); template<class U> constexpr reverse_iterator(const reverse_iterator<U>& u); template<class U> constexpr reverse_iterator& operator=(const reverse_iterator<U>& u); constexpr Iter base() const; constexpr reference operator*() const; constexpr pointer operator->() const requires /* see description */; constexpr reverse_iterator& operator++(); constexpr reverse_iterator operator++(int); constexpr reverse_iterator& operator--(); constexpr reverse_iterator operator--(int); constexpr reverse_iterator operator+ (difference_type n) const; constexpr reverse_iterator& operator+=(difference_type n); constexpr reverse_iterator operator- (difference_type n) const; constexpr reverse_iterator& operator-=(difference_type n); constexpr /* unspecified */ operator[](difference_type n) const; friend constexpr iter_rvalue_reference_t<Iter> iter_move(const reverse_iterator& i) noexcept(/* see description */); template<indirectly_swappable<Iter> Iter2> friend constexpr void iter_swap(const reverse_iterator& x, const reverse_iterator<Iter2>& y) noexcept(/* see description */); protected: Iter current; }; } ``` #### Class template `[std::back\_insert\_iterator](../iterator/back_insert_iterator "cpp/iterator/back insert iterator")` ``` namespace std { template<class Container> class back_insert_iterator { protected: Container* container = nullptr; public: using iterator_category = output_iterator_tag; using value_type = void; using difference_type = ptrdiff_t; using pointer = void; using reference = void; using container_type = Container; constexpr back_insert_iterator() noexcept = default; constexpr explicit back_insert_iterator(Container& x); constexpr back_insert_iterator& operator=(const typename Container::value_type& value); constexpr back_insert_iterator& operator=(typename Container::value_type&& value); constexpr back_insert_iterator& operator*(); constexpr back_insert_iterator& operator++(); constexpr back_insert_iterator operator++(int); }; } ``` #### Class template `[std::front\_insert\_iterator](../iterator/front_insert_iterator "cpp/iterator/front insert iterator")` ``` namespace std { template<class Container> class front_insert_iterator { protected: Container* container = nullptr; public: using iterator_category = output_iterator_tag; using value_type = void; using difference_type = ptrdiff_t; using pointer = void; using reference = void; using container_type = Container; constexpr front_insert_iterator(Container& x) noexcept = default; constexpr explicit front_insert_iterator(Container& x); constexpr front_insert_iterator& operator=(const typename Container::value_type& value); constexpr front_insert_iterator& operator=(typename Container::value_type&& value); constexpr front_insert_iterator& operator*(); constexpr front_insert_iterator& operator++(); constexpr front_insert_iterator operator++(int); }; } ``` #### Class template `[std::insert\_iterator](../iterator/insert_iterator "cpp/iterator/insert iterator")` ``` namespace std { template<class Container> class insert_iterator { protected: Container* container = nullptr; ranges::iterator_t<Container> iter = ranges::iterator_t<Container>(); public: using iterator_category = output_iterator_tag; using value_type = void; using difference_type = ptrdiff_t; using pointer = void; using reference = void; using container_type = Container; insert_iterator() = default; constexpr insert_iterator(Container& x, ranges::iterator_t<Container> i); constexpr insert_iterator& operator=(const typename Container::value_type& value); constexpr insert_iterator& operator=(typename Container::value_type&& value); constexpr insert_iterator& operator*(); constexpr insert_iterator& operator++(); constexpr insert_iterator& operator++(int); }; } ``` #### Class template `[std::move\_iterator](../iterator/move_iterator "cpp/iterator/move iterator")` ``` namespace std { template<class Iter> class move_iterator { public: using iterator_type = Iter; using iterator_concept = /* see description */; using iterator_category = /* see description */; using value_type = iter_value_t<Iter>; using difference_type = iter_difference_t<Iter>; using pointer = Iter; using reference = iter_rvalue_reference_t<Iter>; constexpr move_iterator(); constexpr explicit move_iterator(Iter i); template<class U> constexpr move_iterator(const move_iterator<U>& u); template<class U> constexpr move_iterator& operator=(const move_iterator<U>& u); constexpr iterator_type base() const &; constexpr iterator_type base() &&; constexpr reference operator*() const; constexpr pointer operator->() const; constexpr move_iterator& operator++(); constexpr auto operator++(int); constexpr move_iterator& operator--(); constexpr move_iterator operator--(int); constexpr move_iterator operator+(difference_type n) const; constexpr move_iterator& operator+=(difference_type n); constexpr move_iterator operator-(difference_type n) const; constexpr move_iterator& operator-=(difference_type n); constexpr reference operator[](difference_type n) const; template<sentinel_for<Iter> S> friend constexpr bool operator==(const move_iterator& x, const move_sentinel<S>& y); template<sized_sentinel_for<Iter> S> friend constexpr iter_difference_t<Iter> operator-(const move_sentinel<S>& x, const move_iterator& y); template<sized_sentinel_for<Iter> S> friend constexpr iter_difference_t<Iter> operator-(const move_iterator& x, const move_sentinel<S>& y); friend constexpr iter_rvalue_reference_t<Iter> iter_move(const move_iterator& i) noexcept(noexcept(ranges::iter_move(i.current))); template<indirectly_swappable<Iter> Iter2> friend constexpr void iter_swap(const move_iterator& x, const move_iterator<Iter2>& y) noexcept(noexcept(ranges::iter_swap(x.current, y.current))); private: Iter current; // exposition only }; } ``` #### Class template `[std::move\_sentinel](../iterator/move_sentinel "cpp/iterator/move sentinel")` ``` namespace std { template<semiregular S> class move_sentinel { public: constexpr move_sentinel(); constexpr explicit move_sentinel(S s); template<class S2> requires convertible_to<const S2&, S> constexpr move_sentinel(const move_sentinel<S2>& s); template<class S2> requires assignable_from<S&, const S2&> constexpr move_sentinel& operator=(const move_sentinel<S2>& s); constexpr S base() const; private: S last; // exposition only }; } ``` #### Class template `[std::common\_iterator](../iterator/common_iterator "cpp/iterator/common iterator")` ``` namespace std { template<input_or_output_iterator I, sentinel_for<I> S> requires (!same_as<I, S> && copyable<I>) class common_iterator { public: constexpr common_iterator() = default; constexpr common_iterator(I i); constexpr common_iterator(S s); template<class I2, class S2> requires convertible_to<const I2&, I> && convertible_to<const S2&, S> constexpr common_iterator(const common_iterator<I2, S2>& x); template<class I2, class S2> requires convertible_to<const I2&, I> && convertible_to<const S2&, S> && assignable_from<I&, const I2&> && assignable_from<S&, const S2&> common_iterator& operator=(const common_iterator<I2, S2>& x); decltype(auto) operator*(); decltype(auto) operator*() const requires dereferenceable<const I>; decltype(auto) operator->() const requires /* see description */; common_iterator& operator++(); decltype(auto) operator++(int); template<class I2, sentinel_for<I> S2> requires sentinel_for<S, I2> friend bool operator==( const common_iterator& x, const common_iterator<I2, S2>& y); template<class I2, sentinel_for<I> S2> requires sentinel_for<S, I2> && equality_comparable_with<I, I2> friend bool operator==( const common_iterator& x, const common_iterator<I2, S2>& y); template<sized_sentinel_for<I> I2, sized_sentinel_for<I> S2> requires sized_sentinel_for<S, I2> friend iter_difference_t<I2> operator-( const common_iterator& x, const common_iterator<I2, S2>& y); friend iter_rvalue_reference_t<I> iter_move(const common_iterator& i) noexcept(noexcept(ranges::iter_move(declval<const I&>()))) requires input_iterator<I>; template<indirectly_swappable<I> I2, class S2> friend void iter_swap(const common_iterator& x, const common_iterator<I2, S2>& y) noexcept(noexcept(ranges::iter_swap(declval<const I&>(), declval<const I2&>()))); private: variant<I, S> v_; // exposition only }; template<class I, class S> struct incrementable_traits<common_iterator<I, S>> { using difference_type = iter_difference_t<I>; }; template<input_iterator I, class S> struct iterator_traits<common_iterator<I, S>> { using iterator_concept = /* see description */; using iterator_category = /* see description */; using value_type = iter_value_t<I>; using difference_type = iter_difference_t<I>; using pointer = /* see description */; using reference = iter_reference_t<I>; }; } ``` #### Class `[std::default\_sentinel\_t](../iterator/default_sentinel_t "cpp/iterator/default sentinel t")` ``` namespace std { struct default_sentinel_t { }; } ``` #### Class template `[std::counted\_iterator](../iterator/counted_iterator "cpp/iterator/counted iterator")` ``` namespace std { template<input_or_output_iterator I> class counted_iterator { public: using iterator_type = I; constexpr counted_iterator() = default; constexpr counted_iterator(I x, iter_difference_t<I> n); template<class I2> requires convertible_to<const I2&, I> constexpr counted_iterator(const counted_iterator<I2>& x); template<class I2> requires assignable_from<I&, const I2&> constexpr counted_iterator& operator=(const counted_iterator<I2>& x); constexpr I base() const & requires copy_constructible<I>; constexpr I base() &&; constexpr iter_difference_t<I> count() const noexcept; constexpr decltype(auto) operator*(); constexpr decltype(auto) operator*() const requires dereferenceable<const I>; constexpr auto operator->() const noexcept requires contiguous_iterator<I>; constexpr counted_iterator& operator++(); decltype(auto) operator++(int); constexpr counted_iterator operator++(int) requires forward_iterator<I>; constexpr counted_iterator& operator--() requires bidirectional_iterator<I>; constexpr counted_iterator operator--(int) requires bidirectional_iterator<I>; constexpr counted_iterator operator+(iter_difference_t<I> n) const requires random_access_iterator<I>; friend constexpr counted_iterator operator+( iter_difference_t<I> n, const counted_iterator& x) requires random_access_iterator<I>; constexpr counted_iterator& operator+=(iter_difference_t<I> n) requires random_access_iterator<I>; constexpr counted_iterator operator-(iter_difference_t<I> n) const requires random_access_iterator<I>; template<common_with<I> I2> friend constexpr iter_difference_t<I2> operator-( const counted_iterator& x, const counted_iterator<I2>& y); friend constexpr iter_difference_t<I> operator-( const counted_iterator& x, default_sentinel_t); friend constexpr iter_difference_t<I> operator-( default_sentinel_t, const counted_iterator& y); constexpr counted_iterator& operator-=(iter_difference_t<I> n) requires random_access_iterator<I>; constexpr decltype(auto) operator[](iter_difference_t<I> n) const requires random_access_iterator<I>; template<common_with<I> I2> friend constexpr bool operator==( const counted_iterator& x, const counted_iterator<I2>& y); friend constexpr bool operator==( const counted_iterator& x, default_sentinel_t); template<common_with<I> I2> friend constexpr strong_ordering operator<=>( const counted_iterator& x, const counted_iterator<I2>& y); friend constexpr iter_rvalue_reference_t<I> iter_move(const counted_iterator& i) noexcept(noexcept(ranges::iter_move(i.current))) requires input_iterator<I>; template<indirectly_swappable<I> I2> friend constexpr void iter_swap(const counted_iterator& x, const counted_iterator<I2>& y) noexcept(noexcept(ranges::iter_swap(x.current, y.current))); private: I current = I(); // exposition only iter_difference_t<I> length = 0; // exposition only }; template<input_iterator I> struct iterator_traits<counted_iterator<I>> : iterator_traits<I> { using pointer = void; }; } ``` #### Class `[std::unreachable\_sentinel\_t](../iterator/unreachable_sentinel_t "cpp/iterator/unreachable sentinel t")` ``` namespace std { struct unreachable_sentinel_t { template<weakly_incrementable I> friend constexpr bool operator==(unreachable_sentinel_t, const I&) noexcept { return false; } }; } ``` #### Class template `[std::istream\_iterator](../iterator/istream_iterator "cpp/iterator/istream iterator")` ``` namespace std { template<class T, class CharT = char, class Traits = char_traits<CharT>, class Distance = ptrdiff_t> class istream_iterator { public: using iterator_category = input_iterator_tag; using value_type = T; using difference_type = Distance; using pointer = const T*; using reference = const T&; using char_type = CharT; using traits_type = Traits; using istream_type = basic_istream<CharT, Traits>; constexpr istream_iterator(); constexpr istream_iterator(default_sentinel_t); istream_iterator(istream_type& s); istream_iterator(const istream_iterator& x) = default; ~istream_iterator() = default; istream_iterator& operator=(const istream_iterator&) = default; const T& operator*() const; const T* operator->() const; istream_iterator& operator++(); istream_iterator operator++(int); friend bool operator==(const istream_iterator& i, default_sentinel_t); private: basic_istream<CharT, Traits>* in_stream; // exposition only T value; // exposition only }; } ``` #### Class template `[std::ostream\_iterator](../iterator/ostream_iterator "cpp/iterator/ostream iterator")` ``` namespace std { template<class T, class CharT = char, classTraits = char_traits<CharT>> class ostream_iterator { public: using iterator_category = output_iterator_tag; using value_type = void; using difference_type = ptrdiff_t; using pointer = void; using reference = void; using char_type = CharT; using traits_type = Traits; using ostream_type = basic_ostream<CharT, Traits>; constexpr ostreambuf_iterator() noexcept = default; ostream_iterator(ostream_type& s); ostream_iterator(ostream_type& s, const CharT* delimiter); ostream_iterator(const ostream_iterator& x); ~ostream_iterator(); ostream_iterator& operator=(const ostream_iterator&) = default; ostream_iterator& operator=(const T& value); ostream_iterator& operator*(); ostream_iterator& operator++(); ostream_iterator& operator++(int); private: basic_ostream<CharT, Traits>* out_stream = nullptr; // exposition only const CharT* delim = nullptr; // exposition only }; } ``` #### Class template `[std::istreambuf\_iterator](../iterator/istreambuf_iterator "cpp/iterator/istreambuf iterator")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class istreambuf_iterator { public: using iterator_category = input_iterator_tag; using value_type = CharT; using difference_type = typename Traits::off_type; using pointer = /* unspecified */; using reference = CharT; using char_type = CharT; using traits_type = Traits; using int_type = typename Traits::int_type; using streambuf_type = basic_streambuf<CharT, Traits>; using istream_type = basic_istream<CharT, Traits>; class proxy; // exposition only constexpr istreambuf_iterator() noexcept; constexpr istreambuf_iterator(default_sentinel_t) noexcept; istreambuf_iterator(const istreambuf_iterator&) noexcept = default; ~istreambuf_iterator() = default; istreambuf_iterator(istream_type& s) noexcept; istreambuf_iterator(streambuf_type* s) noexcept; istreambuf_iterator(const proxy& p) noexcept; istreambuf_iterator& operator=(const istreambuf_iterator&) noexcept = default; CharT operator*() const; istreambuf_iterator& operator++(); proxy operator++(int); bool equal(const istreambuf_iterator& b) const; friend bool operator==(const istreambuf_iterator& i, default_sentinel_t s); private: streambuf_type* sbuf_; // exposition only }; template<class CharT, class Traits> class istreambuf_iterator<CharT, Traits>::proxy { // exposition only CharT keep_; basic_streambuf<CharT, Traits>* sbuf_; proxy(CharT c, basic_streambuf<CharT, Traits>* sbuf) : keep_(c), sbuf_(sbuf) { } public: CharT operator*() { return keep_; } }; } ``` #### Class template `[std::ostreambuf\_iterator](../iterator/ostreambuf_iterator "cpp/iterator/ostreambuf iterator")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class ostreambuf_iterator { public: using iterator_category = output_iterator_tag; using value_type = void; using difference_type = ptrdiff_t; using pointer = void; using reference = void; using char_type = CharT; using traits_type = Traits; using streambuf_type = basic_streambuf<CharT, Traits>; using ostream_type = basic_ostream<CharT, Traits>; constexpr ostreambuf_iterator() noexcept = default; ostreambuf_iterator(ostream_type& s) noexcept; ostreambuf_iterator(streambuf_type* s) noexcept; ostreambuf_iterator& operator=(CharT c); ostreambuf_iterator& operator*(); ostreambuf_iterator& operator++(); ostreambuf_iterator& operator++(int); bool failed() const noexcept; private: streambuf_type* sbuf_ = nullptr; // exposition only }; } ``` #### Class template `[std::iterator](../iterator/iterator "cpp/iterator/iterator")` ``` namespace std { template<class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> struct iterator { typedef Category iterator_category; typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; }; } ```
programming_docs
cpp Standard library header <concepts> (C++20) Standard library header <concepts> (C++20) ========================================== This header is part of the [concepts](../concepts "cpp/concepts") library. | | | --- | | Concepts | | Core language concepts | | [same\_as](../concepts/same_as "cpp/concepts/same as") (C++20) | specifies that a type is the same as another type (concept) | | [derived\_from](../concepts/derived_from "cpp/concepts/derived from") (C++20) | specifies that a type is derived from another type (concept) | | [convertible\_to](../concepts/convertible_to "cpp/concepts/convertible to") (C++20) | specifies that a type is implicitly convertible to another type (concept) | | [common\_reference\_with](../concepts/common_reference_with "cpp/concepts/common reference with") (C++20) | specifies that two types share a common reference type (concept) | | [common\_with](../concepts/common_with "cpp/concepts/common with") (C++20) | specifies that two types share a common type (concept) | | [integral](../concepts/integral "cpp/concepts/integral") (C++20) | specifies that a type is an integral type (concept) | | [signed\_integral](../concepts/signed_integral "cpp/concepts/signed integral") (C++20) | specifies that a type is an integral type that is signed (concept) | | [unsigned\_integral](../concepts/unsigned_integral "cpp/concepts/unsigned integral") (C++20) | specifies that a type is an integral type that is unsigned (concept) | | [floating\_point](../concepts/floating_point "cpp/concepts/floating point") (C++20) | specifies that a type is a floating-point type (concept) | | [assignable\_from](../concepts/assignable_from "cpp/concepts/assignable from") (C++20) | specifies that a type is assignable from another type (concept) | | [swappableswappable\_with](../concepts/swappable "cpp/concepts/swappable") (C++20) | specifies that a type can be swapped or that two types can be swapped with each other (concept) | | [destructible](../concepts/destructible "cpp/concepts/destructible") (C++20) | specifies that an object of the type can be destroyed (concept) | | [constructible\_from](../concepts/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) | | [default\_initializable](../concepts/default_initializable "cpp/concepts/default initializable") (C++20) | specifies that an object of a type can be default constructed (concept) | | [move\_constructible](../concepts/move_constructible "cpp/concepts/move constructible") (C++20) | specifies that an object of a type can be move constructed (concept) | | [copy\_constructible](../concepts/copy_constructible "cpp/concepts/copy constructible") (C++20) | specifies that an object of a type can be copy constructed and move constructed (concept) | | Comparison concepts | | [equality\_comparableequality\_comparable\_with](../concepts/equality_comparable "cpp/concepts/equality comparable") (C++20) | specifies that operator `==` is an equivalence relation (concept) | | [totally\_orderedtotally\_ordered\_with](../concepts/totally_ordered "cpp/concepts/totally ordered") (C++20) | specifies that the comparison operators on the type yield a total order (concept) | | Object concepts | | [movable](../concepts/movable "cpp/concepts/movable") (C++20) | specifies that an object of a type can be moved and swapped (concept) | | [copyable](../concepts/copyable "cpp/concepts/copyable") (C++20) | specifies that an object of a type can be copied, moved, and swapped (concept) | | [semiregular](../concepts/semiregular "cpp/concepts/semiregular") (C++20) | specifies that an object of a type can be copied, moved, swapped, and default constructed (concept) | | [regular](../concepts/regular "cpp/concepts/regular") (C++20) | specifies that a type is regular, that is, it is both [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") and [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable") (concept) | | Callable concepts | | [invocableregular\_invocable](../concepts/invocable "cpp/concepts/invocable") (C++20) | specifies that a callable type can be invoked with a given set of argument types (concept) | | [predicate](../concepts/predicate "cpp/concepts/predicate") (C++20) | specifies that a callable type is a Boolean predicate (concept) | | [relation](../concepts/relation "cpp/concepts/relation") (C++20) | specifies that a callable type is a binary relation (concept) | | [equivalence\_relation](../concepts/equivalence_relation "cpp/concepts/equivalence relation") (C++20) | specifies that a [`relation`](../concepts/relation "cpp/concepts/relation") imposes an equivalence relation (concept) | | [strict\_weak\_order](../concepts/strict_weak_order "cpp/concepts/strict weak order") (C++20) | specifies that a [`relation`](../concepts/relation "cpp/concepts/relation") imposes a strict weak ordering (concept) | | Customization point objects | | [ranges::swap](../utility/ranges/swap "cpp/utility/ranges/swap") (C++20) | swaps the values of two objects (customization point object) | ### Synopsis ``` namespace std { // language-related concepts // concept same_as template<class T, class U> concept same_as = /* see description */; // concept derived_from template<class Derived, class Base> concept derived_from = /* see description */; // concept convertible_to template<class From, class To> concept convertible_to = /* see description */; // concept common_reference_with template<class T, class U> concept common_reference_with = /* see description */; // concept common_with template<class T, class U> concept common_with = /* see description */; // arithmetic concepts template<class T> concept integral = /* see description */; template<class T> concept signed_integral = /* see description */; template<class T> concept unsigned_integral = /* see description */; template<class T> concept floating_point = /* see description */; // concept assignable_from template<class LHS, class RHS> concept assignable_from = /* see description */; // concept swappable namespace ranges { inline namespace /* unspecified */ { inline constexpr /* unspecified */ swap = /* unspecified */; } } template<class T> concept swappable = /* see description */; template<class T, class U> concept swappable_with = /* see description */; // concept destructible template<class T> concept destructible = /* see description */; // concept constructible_from template<class T, class... Args> concept constructible_from = /* see description */; // concept default_initializable template<class T> concept default_initializable = /* see description */; // concept move_constructible template<class T> concept move_constructible = /* see description */; // concept copy_constructible template<class T> concept copy_constructible = /* see description */; // comparison concepts // concept equality_comparable template<class T> concept equality_comparable = /* see description */; template<class T, class U> concept equality_comparable_with = /* see description */; // concept totally_ordered template<class T> concept totally_ordered = /* see description */; template<class T, class U> concept totally_ordered_with = /* see description */; // object concepts template<class T> concept movable = /* see description */; template<class T> concept copyable = /* see description */; template<class T> concept semiregular = /* see description */; template<class T> concept regular = /* see description */; // callable concepts // concept invocable template<class F, class... Args> concept invocable = /* see description */; // concept regular_invocable template<class F, class... Args> concept regular_invocable = /* see description */; // concept predicate template<class F, class... Args> concept predicate = /* see description */; // concept relation template<class R, class T, class U> concept relation = /* see description */; // concept equivalence_relation template<class R, class T, class U> concept equivalence_relation = /* see description */; // concept strict_weak_order template<class R, class T, class U> concept strict_weak_order = /* see description */; } ``` #### Concept [`same_as`](../concepts/same_as "cpp/concepts/same as") ``` template<class T, class U> concept __SameImpl = is_same_v<T, U>; // exposition only template<class T, class U> concept same_as = __SameImpl<T, U> && __SameImpl<U, T>; ``` #### Concept [`derived_from`](../concepts/derived_from "cpp/concepts/derived from") ``` template<class Derived, class Base> concept derived_from = is_base_of_v<Base, Derived> && is_convertible_v<const volatile Derived*, const volatile Base*>; ``` #### Concept [`convertible_to`](../concepts/convertible_to "cpp/concepts/convertible to") ``` template<class From, class To> concept convertible_to = is_convertible_v<From, To> && requires(From (&f)()) { static_cast<To>(f()); }; ``` #### Concept [`common_reference_with`](../concepts/common_reference_with "cpp/concepts/common reference with") ``` template<class T, class U> concept common_reference_with = same_as<common_reference_t<T, U>, common_reference_t<U, T>> && convertible_to<T, common_reference_t<T, U>> && convertible_to<U, common_reference_t<T, U>>; ``` #### Concept [`common_with`](../concepts/common_with "cpp/concepts/common with") ``` template<class T, class U> concept common_with = same_as<common_type_t<T, U>, common_type_t<U, T>> && requires { static_cast<common_type_t<T, U>>(declval<T>()); static_cast<common_type_t<T, U>>(declval<U>()); } && common_reference_with< add_lvalue_reference_t<const T>, add_lvalue_reference_t<const U>> && common_reference_with< add_lvalue_reference_t<common_type_t<T, U>>, common_reference_t< add_lvalue_reference_t<const T>, add_lvalue_reference_t<const U>>>; ``` #### Concept [`integral`](../concepts/integral "cpp/concepts/integral") ``` template<class T> concept integral = is_integral_v<T>; ``` #### Concept [`signed_integral`](../concepts/signed_integral "cpp/concepts/signed integral") ``` template<class T> concept signed_integral = integral<T> && is_signed_v<T>; ``` #### Concept [`unsigned_integral`](../concepts/unsigned_integral "cpp/concepts/unsigned integral") ``` template<class T> concept unsigned_integral = integral<T> && !signed_integral<T>; ``` #### Concept [`floating_point`](../concepts/floating_point "cpp/concepts/floating point") ``` template<class T> concept floating_point = is_floating_point_v<T>; ``` #### Concept [`assignable_from`](../concepts/assignable_from "cpp/concepts/assignable from") ``` template<class LHS, class RHS> concept assignable_from = is_lvalue_reference_v<LHS> && common_reference_with< const remove_reference_t<LHS>&, const remove_reference_t<RHS>&> && requires(LHS lhs, RHS&& rhs) { { lhs = std::forward<RHS>(rhs) } -> same_as<LHS>; ``` #### Concept [`swappable`](../concepts/swappable "cpp/concepts/swappable") ``` template<class T> concept swappable = requires(T& a, T& b) { ranges::swap(a, b); }; ``` #### Concept [`swappable_with`](../concepts/swappable "cpp/concepts/swappable") ``` template<class T, class U> concept swappable_with = common_reference_with<const remove_reference_t<T>&, const remove_reference_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)); }; ``` #### Concept [`destructible`](../concepts/destructible "cpp/concepts/destructible") ``` template<class T> concept destructible = is_nothrow_destructible_v<T>; ``` #### Concept [`constructible_from`](../concepts/constructible_from "cpp/concepts/constructible from") ``` template<class T, class... Args> concept constructible_from = destructible<T> && is_constructible_v<T, Args...>; ``` #### Concept [`default_initializable`](../concepts/default_initializable "cpp/concepts/default initializable") ``` template<class T> inline constexpr bool __is_default_initializable = /* see description */; // exposition only template<class T> concept default_initializable = constructible_from<T> && requires{ T{}; } && __is_default_initializable<T>; ``` #### Concept [`move_constructible`](../concepts/move_constructible "cpp/concepts/move constructible") ``` template<class T> concept move_constructible = constructible_from<T, T> && convertible_to<T, T>; ``` #### Concept [`copy_constructible`](../concepts/copy_constructible "cpp/concepts/copy constructible") ``` template<class T> concept copy_constructible = move_constructible<T> && constructible_from<T, T&> && convertible_to<T&, T> && constructible_from<T, const T&> && convertible_to<const T&, T> && constructible_from<T, const T> && convertible_to<const T, T>; ``` #### Concept [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable") ``` template<class T, class U> concept __WeaklyEqualityComparableWith = // exposition only requires(const remove_reference_t<T>& t, const remove_reference_t<U>& u) { { t == u } -> boolean-testable; { t != u } -> boolean-testable; { u == t } -> boolean-testable; { u != t } -> boolean-testable; }; template<class T> concept equality_comparable = __WeaklyEqualityComparableWith<T, T>; ``` #### Concept [`equality_comparable_with`](../concepts/equality_comparable "cpp/concepts/equality comparable") ``` template<class T, class U> concept equality_comparable_with = equality_comparable<T> && equality_comparable<U> && common_reference_with<const remove_reference_t<T>&, const remove_reference_t<U>&> && equality_comparable< common_reference_t< const remove_reference_t<T>&, const remove_reference_t<U>&>> && __WeaklyEqualityComparableWith<T, U>; ``` #### Concept [`totally_ordered`](../concepts/totally_ordered "cpp/concepts/totally ordered") ``` template<class T> concept totally_ordered = equality_comparable<T> && requires(const remove_reference_t<T>& a, const remove_reference_t<T>& b) { { a < b } -> boolean-testable; { a > b } -> boolean-testable; { a <= b } -> boolean-testable; { a >= b } -> boolean-testable; }; ``` #### Concept [`totally_ordered_with`](../concepts/totally_ordered "cpp/concepts/totally ordered") ``` template<class T, class U> concept totally_ordered_with = totally_ordered<T> && totally_ordered<U> && common_reference_with<const remove_reference_t<T>&, const remove_reference_t<U>&> && totally_ordered< common_reference_t< const remove_reference_t<T>&, const remove_reference_t<U>&>> && equality_comparable_with<T, U> && requires(const remove_reference_t<T>& t, const remove_reference_t<U>& u) { { t < u } -> boolean-testable; { t > u } -> boolean-testable; { t <= u } -> boolean-testable; { t >= u } -> boolean-testable; { u < t } -> boolean-testable; { u > t } -> boolean-testable; { u <= t } -> boolean-testable; { u >= t } -> boolean-testable; }; ``` #### Concept [`movable`](../concepts/movable "cpp/concepts/movable") ``` template<class T> concept movable = is_object_v<T> && move_constructible<T> && assignable_from<T&, T> && swappable<T>; ``` #### Concept [`copyable`](../concepts/copyable "cpp/concepts/copyable") ``` template<class T> concept copyable = copy_constructible<T> && movable<T> && assignable_from<T&, T&> && assignable_from<T&, const T&> && assignable_from<T&, const T>; ``` #### Concept [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") ``` template<class T> concept semiregular = copyable<T> && default_initializable<T>; ``` #### Concept [`regular`](../concepts/regular "cpp/concepts/regular") ``` template<class T> concept regular = semiregular<T> && equality_comparable<T>; ``` #### Concept [`invocable`](../concepts/invocable "cpp/concepts/invocable") ``` template<class F, class... Args> concept invocable = requires(F&& f, Args&&... args) { invoke(std::forward<F>(f), std::forward<Args>(args)...); // not required to be equality-preserving }; ``` #### Concept [`regular_invocable`](../concepts/invocable "cpp/concepts/invocable") ``` template<class F, class... Args> concept regular_invocable = invocable<F, Args...>; ``` #### Concept [`predicate`](../concepts/predicate "cpp/concepts/predicate") ``` template<class F, class... Args> concept predicate = regular_invocable<F, Args...> && boolean-testable<invoke_result_t<F, Args...>>; ``` #### Concept [`relation`](../concepts/relation "cpp/concepts/relation") ``` template<class R, class T, class U> concept relation = predicate<R, T, T> && predicate<R, U, U> && predicate<R, T, U> && predicate<R, U, T>; ``` #### Concept [`equivalence_relation`](../concepts/equivalence_relation "cpp/concepts/equivalence relation") ``` template<class R, class T, class U> concept equivalence_relation = relation<R, T, U>; ``` #### Concept [`strict_weak_order`](../concepts/strict_weak_order "cpp/concepts/strict weak order") ``` template<class R, class T, class U> concept strict_weak_order = relation<R, T, U>; ``` cpp Standard library header <fstream> Standard library header <fstream> ================================= This header is part of the [Input/Output](../io "cpp/io") library. | | | --- | | Classes | | [basic\_filebuf](../io/basic_filebuf "cpp/io/basic filebuf") | implements raw file device (class template) | | [basic\_ifstream](../io/basic_ifstream "cpp/io/basic ifstream") | implements high-level file stream input operations (class template) | | [basic\_ofstream](../io/basic_ofstream "cpp/io/basic ofstream") | implements high-level file stream output operations (class template) | | [basic\_fstream](../io/basic_fstream "cpp/io/basic fstream") | implements high-level file stream input/output operations (class template) | | `filebuf` | `[std::basic\_filebuf](http://en.cppreference.com/w/cpp/io/basic_filebuf)<char>`(typedef) | | `wfilebuf` | `[std::basic\_filebuf](http://en.cppreference.com/w/cpp/io/basic_filebuf)<wchar\_t>`(typedef) | | `ifstream` | `[std::basic\_ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream)<char>`(typedef) | | `wifstream` | `[std::basic\_ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream)<wchar\_t>`(typedef) | | `ofstream` | `[std::basic\_ofstream](http://en.cppreference.com/w/cpp/io/basic_ofstream)<char>`(typedef) | | `wofstream` | `[std::basic\_ofstream](http://en.cppreference.com/w/cpp/io/basic_ofstream)<wchar\_t>`(typedef) | | `fstream` | `[std::basic\_fstream](http://en.cppreference.com/w/cpp/io/basic_fstream)<char>`(typedef) | | `wfstream` | `[std::basic\_fstream](http://en.cppreference.com/w/cpp/io/basic_fstream)<wchar\_t>`(typedef) | | Functions | | [std::swap(std::basic\_filebuf)](../io/basic_filebuf/swap2 "cpp/io/basic filebuf/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_ifstream)](../io/basic_ifstream/swap2 "cpp/io/basic ifstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_ofstream)](../io/basic_ofstream/swap2 "cpp/io/basic ofstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::basic\_fstream)](../io/basic_fstream/swap2 "cpp/io/basic fstream/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Synopsis ``` namespace std { template<class charT, class traits = char_traits<charT>> class basic_filebuf; using filebuf = basic_filebuf<char>; using wfilebuf = basic_filebuf<wchar_t>; template<class charT, class traits = char_traits<charT>> class basic_ifstream; using ifstream = basic_ifstream<char>; using wifstream = basic_ifstream<wchar_t>; template<class charT, class traits = char_traits<charT>> class basic_ofstream; using ofstream = basic_ofstream<char>; using wofstream = basic_ofstream<wchar_t>; template<class charT, class traits = char_traits<charT>> class basic_fstream; using fstream = basic_fstream<char>; using wfstream = basic_fstream<wchar_t>; } ``` #### Class template `[std::basic\_filebuf](../io/basic_filebuf "cpp/io/basic filebuf")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_filebuf : public basic_streambuf<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors/destructor basic_filebuf(); basic_filebuf(const basic_filebuf&) = delete; basic_filebuf(basic_filebuf&& rhs); virtual ~basic_filebuf(); // assign and swap basic_filebuf& operator=(const basic_filebuf&) = delete; basic_filebuf& operator=(basic_filebuf&& rhs); void swap(basic_filebuf& rhs); // members bool is_open() const; basic_filebuf* open(const char* s, ios_base::openmode mode); basic_filebuf* open(const filesystem::path::value_type* s, ios_base::openmode mode); // wide systems only basic_filebuf* open(const string& s, ios_base::openmode mode); basic_filebuf* open(const filesystem::path& s, ios_base::openmode mode); basic_filebuf* close(); protected: // overridden virtual functions streamsize showmanyc() override; int_type underflow() override; int_type uflow() override; int_type pbackfail(int_type c = Traits::eof()) override; int_type overflow (int_type c = Traits::eof()) override; basic_streambuf<CharT, Traits>* setbuf(char_type* s, streamsize n) override; pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out) override; pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out) override; int sync() override; void imbue(const locale& loc) override; }; template<class CharT, class Traits> void swap(basic_filebuf<CharT, Traits>& x, basic_filebuf<CharT, Traits>& y); } ``` #### Class template `[std::basic\_ifstream](../io/basic_ifstream "cpp/io/basic ifstream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ifstream : public basic_istream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors basic_ifstream(); explicit basic_ifstream(const char* s, ios_base::openmode mode = ios_base::in); explicit basic_ifstream(const filesystem::path::value_type* s, ios_base::openmode mode = ios_base::in);// wide systems only explicit basic_ifstream(const string& s, ios_base::openmode mode = ios_base::in); explicit basic_ifstream(const filesystem::path& s, ios_base::openmode mode = ios_base::in); basic_ifstream(const basic_ifstream&) = delete; basic_ifstream(basic_ifstream&& rhs); // assign and swap basic_ifstream& operator=(const basic_ifstream&) = delete; basic_ifstream& operator=(basic_ifstream&& rhs); void swap(basic_ifstream& rhs); // members basic_filebuf<CharT, Traits>* rdbuf() const; bool is_open() const; void open(const char* s, ios_base::openmode mode = ios_base::in); void open(const filesystem::path::value_type* s, ios_base::openmode mode = ios_base::in); // wide systems only void open(const string& s, ios_base::openmode mode = ios_base::in); void open(const filesystem::path& s, ios_base::openmode mode = ios_base::in); void close(); private: basic_filebuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits> void swap(basic_ifstream<CharT, Traits>& x, basic_ifstream<CharT, Traits>& y); } ``` #### Class template `[std::basic\_ofstream](../io/basic_ofstream "cpp/io/basic ofstream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_ofstream : public basic_ostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors basic_ofstream(); explicit basic_ofstream(const char* s, ios_base::openmode mode = ios_base::out); explicit basic_ofstream(const filesystem::path::value_type* s, // wide systems only ios_base::openmode mode = ios_base::out); explicit basic_ofstream(const string& s, ios_base::openmode mode = ios_base::out); explicit basic_ofstream(const filesystem::path& s, ios_base::openmode mode = ios_base::out); basic_ofstream(const basic_ofstream&) = delete; basic_ofstream(basic_ofstream&& rhs); // assign and swap basic_ofstream& operator=(const basic_ofstream&) = delete; basic_ofstream& operator=(basic_ofstream&& rhs); void swap(basic_ofstream& rhs); // members basic_filebuf<CharT, Traits>* rdbuf() const; bool is_open() const; void open(const char* s, ios_base::openmode mode = ios_base::out); void open(const filesystem::path::value_type* s, ios_base::openmode mode = ios_base::out); // wide systems only void open(const string& s, ios_base::openmode mode = ios_base::out); void open(const filesystem::path& s, ios_base::openmode mode = ios_base::out); void close(); private: basic_filebuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits> void swap(basic_ofstream<CharT, Traits>& x, basic_ofstream<CharT, Traits>& y); } ``` #### Class template `[std::basic\_fstream](../io/basic_fstream "cpp/io/basic fstream")` ``` namespace std { template<class CharT, class Traits = char_traits<CharT>> class basic_fstream : public basic_iostream<CharT, Traits> { public: using char_type = CharT; using int_type = typename Traits::int_type; using pos_type = typename Traits::pos_type; using off_type = typename Traits::off_type; using traits_type = Traits; // constructors basic_fstream(); explicit basic_fstream( const char* s, ios_base::openmode mode = ios_base::in | ios_base::out); explicit basic_fstream( const filesystem::path::value_type* s, ios_base::openmode mode = ios_base::in | ios_base::out); // wide systems only explicit basic_fstream( const string& s, ios_base::openmode mode = ios_base::in | ios_base::out); explicit basic_fstream( const filesystem::path& s, ios_base::openmode mode = ios_base::in | ios_base::out); basic_fstream(const basic_fstream&) = delete; basic_fstream(basic_fstream&& rhs); // assign and swap basic_fstream& operator=(const basic_fstream&) = delete; basic_fstream& operator=(basic_fstream&& rhs); void swap(basic_fstream& rhs); // members basic_filebuf<CharT, Traits>* rdbuf() const; bool is_open() const; void open( const char* s, ios_base::openmode mode = ios_base::in | ios_base::out); void open( const filesystem::path::value_type* s, ios_base::openmode mode = ios_base::in | ios_base::out); // wide systems only void open( const string& s, ios_base::openmode mode = ios_base::in | ios_base::out); void open( const filesystem::path& s, ios_base::openmode mode = ios_base::in | ios_base::out); void close(); private: basic_filebuf<CharT, Traits> sb; // exposition only }; template<class CharT, class Traits> void swap(basic_fstream<CharT, Traits>& x, basic_fstream<CharT, Traits>& y); } ```
programming_docs
cpp Standard library header <latch> (C++20) Standard library header <latch> (C++20) ======================================= This header is part of the [thread support](../thread "cpp/thread") library. | | | --- | | Classes | | [latch](../thread/latch "cpp/thread/latch") (C++20) | single-use thread barrier (class) | ### Synopsis ``` namespace std { class latch; } ``` #### Class `[std::latch](../thread/latch "cpp/thread/latch")` ``` namespace std { class latch { public: static constexpr ptrdiff_t max() noexcept; constexpr explicit latch(ptrdiff_t expected); ~latch(); latch(const latch&) = delete; latch& operator=(const latch&) = delete; void count_down(ptrdiff_t update = 1); bool try_wait() const noexcept; void wait() const; void arrive_and_wait(ptrdiff_t update = 1); private: ptrdiff_t counter; // exposition only }; } ``` cpp Standard library header <stdatomic.h> Standard library header <stdatomic.h> ===================================== This header was originally in the C standard library. This header is part of the [concurrency support](../thread "cpp/thread") library. It is unspecified whether `<stdatomic.h>` provides any declarations in namespace `std`. | | | --- | | Macros | | [\_Atomic](../atomic/atomic "cpp/atomic/atomic") (C++23) | compatibility macro such that `_Atomic(T)` is identical to `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>` (function macro) | | [ATOMIC\_FLAG\_INIT](../atomic/atomic_flag_init "cpp/atomic/ATOMIC FLAG INIT") (C++11) | initializes an `[std::atomic\_flag](../atomic/atomic_flag "cpp/atomic/atomic flag")` to `false` (macro constant) | | Types | | [atomic\_flag](../atomic/atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [memory\_order](../atomic/memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [atomic\_bool](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<bool>` (typedef) | | [atomic\_char](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char>` (typedef) | | [atomic\_schar](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<signed char>` (typedef) | | [atomic\_uchar](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned char>` (typedef) | | [atomic\_short](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<short>` (typedef) | | [atomic\_ushort](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned short>` (typedef) | | [atomic\_int](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<int>` (typedef) | | [atomic\_uint](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned int>` (typedef) | | [atomic\_long](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<long>` (typedef) | | [atomic\_ulong](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned long>` (typedef) | | [atomic\_llong](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<long long>` (typedef) | | [atomic\_ullong](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned long long>` (typedef) | | [atomic\_char8\_t](../atomic/atomic "cpp/atomic/atomic") (C++20) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char8_t>` (typedef) | | [atomic\_char16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char16\_t>` (typedef) | | [atomic\_char32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char32\_t>` (typedef) | | [atomic\_wchar\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<wchar\_t>` (typedef) | | [atomic\_int8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_intptr\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::intptr\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uintptr\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uintptr\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_size\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>` (typedef) | | [atomic\_ptrdiff\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)>` (typedef) | | [atomic\_intmax\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::intmax\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uintmax\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | Functions | | [atomic\_is\_lock\_free](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (C++11) | checks if the atomic type's operations are lock-free (function template) | | [atomic\_storeatomic\_store\_explicit](../atomic/atomic_store "cpp/atomic/atomic store") (C++11)(C++11) | atomically replaces the value of the atomic object with a non-atomic argument (function template) | | [atomic\_loadatomic\_load\_explicit](../atomic/atomic_load "cpp/atomic/atomic load") (C++11)(C++11) | atomically obtains the value stored in an atomic object (function template) | | [atomic\_exchangeatomic\_exchange\_explicit](../atomic/atomic_exchange "cpp/atomic/atomic exchange") (C++11)(C++11) | atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template) | | [atomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicitatomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicit](../atomic/atomic_compare_exchange "cpp/atomic/atomic compare exchange") (C++11)(C++11)(C++11)(C++11) | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (function template) | | [atomic\_fetch\_addatomic\_fetch\_add\_explicit](../atomic/atomic_fetch_add "cpp/atomic/atomic fetch add") (C++11)(C++11) | adds a non-atomic value to an atomic object and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](../atomic/atomic_fetch_sub "cpp/atomic/atomic fetch sub") (C++11)(C++11) | subtracts a non-atomic value from an atomic object and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_andatomic\_fetch\_and\_explicit](../atomic/atomic_fetch_and "cpp/atomic/atomic fetch and") (C++11)(C++11) | replaces the atomic object with the result of bitwise AND with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_oratomic\_fetch\_or\_explicit](../atomic/atomic_fetch_or "cpp/atomic/atomic fetch or") (C++11)(C++11) | replaces the atomic object with the result of bitwise OR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](../atomic/atomic_fetch_xor "cpp/atomic/atomic fetch xor") (C++11)(C++11) | replaces the atomic object with the result of bitwise XOR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](../atomic/atomic_flag_test_and_set "cpp/atomic/atomic flag test and set") (C++11)(C++11) | atomically sets the flag to `true` and returns its previous value (function) | | [atomic\_flag\_clearatomic\_flag\_clear\_explicit](../atomic/atomic_flag_clear "cpp/atomic/atomic flag clear") (C++11)(C++11) | atomically sets the value of the flag to `false` (function) | | [atomic\_thread\_fence](../atomic/atomic_thread_fence "cpp/atomic/atomic thread fence") (C++11) | generic memory order-dependent fence synchronization primitive (function) | | [atomic\_signal\_fence](../atomic/atomic_signal_fence "cpp/atomic/atomic signal fence") (C++11) | fence between a thread and a signal handler executed in the same thread (function) | ### Synopsis ``` template<class T> using __std_atomic = std::atomic<T>; // exposition only #define _Atomic(T) __std_atomic<T> #define ATOMIC_BOOL_LOCK_FREE /* see description */ #define ATOMIC_CHAR_LOCK_FREE /* see description */ #define ATOMIC_CHAR16_T_LOCK_FREE /* see description */ #define ATOMIC_CHAR32_T_LOCK_FREE /* see description */ #define ATOMIC_WCHAR_T_LOCK_FREE /* see description */ #define ATOMIC_SHORT_LOCK_FREE /* see description */ #define ATOMIC_INT_LOCK_FREE /* see description */ #define ATOMIC_LONG_LOCK_FREE /* see description */ #define ATOMIC_LLONG_LOCK_FREE /* see description */ #define ATOMIC_POINTER_LOCK_FREE /* see description */ using std::memory_order; // see description using std::memory_order_relaxed; // see description using std::memory_order_consume; // see description using std::memory_order_acquire; // see description using std::memory_order_release; // see description using std::memory_order_acq_rel; // see description using std::memory_order_seq_cst; // see description using std::atomic_flag; // see description using std::atomic_bool; // see description using std::atomic_char; // see description using std::atomic_schar; // see description using std::atomic_uchar; // see description using std::atomic_short; // see description using std::atomic_ushort; // see description using std::atomic_int; // see description using std::atomic_uint; // see description using std::atomic_long; // see description using std::atomic_ulong; // see description using std::atomic_llong; // see description using std::atomic_ullong; // see description using std::atomic_char8_t; // see description using std::atomic_char16_t; // see description using std::atomic_char32_t; // see description using std::atomic_wchar_t; // see description using std::atomic_int8_t; // see description using std::atomic_uint8_t; // see description using std::atomic_int16_t; // see description using std::atomic_uint16_t; // see description using std::atomic_int32_t; // see description using std::atomic_uint32_t; // see description using std::atomic_int64_t; // see description using std::atomic_uint64_t; // see description using std::atomic_int_least8_t; // see description using std::atomic_uint_least8_t; // see description using std::atomic_int_least16_t; // see description using std::atomic_uint_least16_t; // see description using std::atomic_int_least32_t; // see description using std::atomic_uint_least32_t; // see description using std::atomic_int_least64_t; // see description using std::atomic_uint_least64_t; // see description using std::atomic_int_fast8_t; // see description using std::atomic_uint_fast8_t; // see description using std::atomic_int_fast16_t; // see description using std::atomic_uint_fast16_t; // see description using std::atomic_int_fast32_t; // see description using std::atomic_uint_fast32_t; // see description using std::atomic_int_fast64_t; // see description using std::atomic_uint_fast64_t; // see description using std::atomic_intptr_t; // see description using std::atomic_uintptr_t; // see description using std::atomic_size_t; // see description using std::atomic_ptrdiff_t; // see description using std::atomic_intmax_t; // see description using std::atomic_uintmax_t; // see description using std::atomic_is_lock_free; // see description using std::atomic_load; // see description using std::atomic_load_explicit; // see description using std::atomic_store; // see description using std::atomic_store_explicit; // see description using std::atomic_exchange; // see description using std::atomic_exchange_explicit; // see description using std::atomic_compare_exchange_strong; // see description using std::atomic_compare_exchange_strong_explicit; // see description using std::atomic_compare_exchange_weak; // see description using std::atomic_compare_exchange_weak_explicit; // see description using std::atomic_fetch_add; // see description using std::atomic_fetch_add_explicit; // see description using std::atomic_fetch_sub; // see description using std::atomic_fetch_sub_explicit; // see description using std::atomic_fetch_or; // see description using std::atomic_fetch_or_explicit; // see description using std::atomic_fetch_xor; // see description using std::atomic_fetch_xor_explicit; // see description using std::atomic_fetch_and; // see description using std::atomic_fetch_and_explicit; // see description using std::atomic_flag_test_and_set; // see description using std::atomic_flag_test_and_set_explicit; // see description using std::atomic_flag_clear; // see description using std::atomic_flag_clear_explicit; // see description #define ATOMIC_FLAG_INIT /* see description */ using std::atomic_thread_fence; // see description using std::atomic_signal_fence; // see description ```
programming_docs
cpp Standard library header <limits> Standard library header <limits> ================================ This header is part of the [type support](../types "cpp/types") library. ### Declarations | | | | --- | --- | | [numeric\_limits](../types/numeric_limits "cpp/types/numeric limits") | provides an interface to query properties of all fundamental numeric types. (class template) | | [float\_round\_style](../types/numeric_limits/float_round_style "cpp/types/numeric limits/float round style") | indicates floating-point rounding modes (enum) | | [float\_denorm\_style](../types/numeric_limits/float_denorm_style "cpp/types/numeric limits/float denorm style") | indicates floating-point denormalization modes (enum) | ### Synopsis ``` namespace std { template<class T> class numeric_limits; enum float_round_style { round_indeterminate = -1, round_toward_zero = 0, round_to_nearest = 1, round_toward_infinity = 2, round_toward_neg_infinity = 3, }; enum float_denorm_style { denorm_indeterminate = -1, denorm_absent = 0, denorm_present = 1 }; template<> class numeric_limits<bool>; template<> class numeric_limits<char>; template<> class numeric_limits<signed char>; template<> class numeric_limits<unsigned char>; template<> class numeric_limits<char8_t>; template<> class numeric_limits<char16_t>; template<> class numeric_limits<char32_t>; template<> class numeric_limits<wchar_t>; template<> class numeric_limits<short>; template<> class numeric_limits<int>; template<> class numeric_limits<long>; template<> class numeric_limits<long long>; template<> class numeric_limits<unsigned short>; template<> class numeric_limits<unsigned int>; template<> class numeric_limits<unsigned long>; template<> class numeric_limits<unsigned long long>; template<> class numeric_limits<float>; template<> class numeric_limits<double>; template<> class numeric_limits<long double>; } ``` #### Class template `[std::numeric\_limits](../types/numeric_limits "cpp/types/numeric limits")` ``` template<class T> class numeric_limits { public: static constexpr bool is_specialized = false; static constexpr T min() noexcept { return T(); } static constexpr T max() noexcept { return T(); } static constexpr T lowest() noexcept { return T(); } static constexpr int digits = 0; static constexpr int digits10 = 0; static constexpr int max_digits10 = 0; static constexpr bool is_signed = false; static constexpr bool is_integer = false; static constexpr bool is_exact = false; static constexpr int radix = 0; static constexpr T epsilon() noexcept { return T(); } static constexpr T round_error() noexcept { return T(); } static constexpr int min_exponent = 0; static constexpr int min_exponent10 = 0; static constexpr int max_exponent = 0; static constexpr int max_exponent10 = 0; static constexpr bool has_infinity = false; static constexpr bool has_quiet_NaN = false; static constexpr bool has_signaling_NaN = false; static constexpr float_denorm_style has_denorm = denorm_absent; static constexpr bool has_denorm_loss = false; static constexpr T infinity() noexcept { return T(); } static constexpr T quiet_NaN() noexcept { return T(); } static constexpr T signaling_NaN() noexcept { return T(); } static constexpr T denorm_min() noexcept { return T(); } static constexpr bool is_iec559 = false; static constexpr bool is_bounded = false; static constexpr bool is_modulo = false; static constexpr bool traps = false; static constexpr bool tinyness_before = false; static constexpr float_round_style round_style = round_toward_zero; }; ``` #### Specialization `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<bool>` ``` template<> class numeric_limits<bool> { public: static constexpr bool is_specialized = true; static constexpr bool min() noexcept { return false; } static constexpr bool max() noexcept { return true; } static constexpr bool lowest() noexcept { return false; } static constexpr int digits = 1; static constexpr int digits10 = 0; static constexpr int max_digits10 = 0; static constexpr bool is_signed = false; static constexpr bool is_integer = true; static constexpr bool is_exact = true; static constexpr int radix = 2; static constexpr bool epsilon() noexcept { return 0; } static constexpr bool round_error() noexcept { return 0; } static constexpr int min_exponent = 0; static constexpr int min_exponent10 = 0; static constexpr int max_exponent = 0; static constexpr int max_exponent10 = 0; static constexpr bool has_infinity = false; static constexpr bool has_quiet_NaN = false; static constexpr bool has_signaling_NaN = false; static constexpr float_denorm_style has_denorm = denorm_absent; static constexpr bool has_denorm_loss = false; static constexpr bool infinity() noexcept { return 0; } static constexpr bool quiet_NaN() noexcept { return 0; } static constexpr bool signaling_NaN() noexcept { return 0; } static constexpr bool denorm_min() noexcept { return 0; } static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true; static constexpr bool is_modulo = false; static constexpr bool traps = false; static constexpr bool tinyness_before = false; static constexpr float_round_style round_style = round_toward_zero; }; ``` cpp Standard library header <array> (C++11) Standard library header <array> (C++11) ======================================= This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [array](../container/array "cpp/container/array") (C++11) | static contiguous array (class template) | | [tuple\_size](../utility/tuple_size "cpp/utility/tuple size") (C++11) | obtains the number of elements of a tuple-like type (class template) | | [tuple\_element](../utility/tuple_element "cpp/utility/tuple element") (C++11) | obtains the element types of a tuple-like type (class template) | | [std::tuple\_size<std::array>](../container/array/tuple_size "cpp/container/array/tuple size") (C++11) | obtains the size of an `array` (class template specialization) | | [std::tuple\_element<std::array>](../container/array/tuple_element "cpp/container/array/tuple element") (C++11) | obtains the type of the elements of `array` (class template specialization) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/array/operator_cmp "cpp/container/array/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the array (function template) | | [std::swap(std::array)](../container/array/swap2 "cpp/container/array/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [to\_array](../container/array/to_array "cpp/container/array/to array") (C++20) | creates a `std::array` object from a built-in array (function template) | | [std::get(std::array)](../container/array/get "cpp/container/array/get") (C++11) | accesses an element of an `array` (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template array template<class T, size_t N> struct array; template<class T, size_t N> constexpr bool operator==(const array<T, N>& x, const array<T, N>& y); template<class T, size_t N> constexpr /*synth-three-way-result*/<T> operator<=>(const array<T, N>& x, const array<T, N>& y); // specialized algorithms template<class T, size_t N> constexpr void swap(array<T, N>& x, array<T, N>& y) noexcept(noexcept(x.swap(y))); // array creation functions template<class T, size_t N> constexpr array<remove_cv_t<T>, N> to_array(T (&a)[N]); template<class T, size_t N> constexpr array<remove_cv_t<T>, N> to_array(T (&&a)[N]); // tuple interface template<class T> struct tuple_size; template<size_t I, class T> struct tuple_element; template<class T, size_t N> struct tuple_size<array<T, N>>; template<size_t I, class T, size_t N> struct tuple_element<I, array<T, N>>; template<size_t I, class T, size_t N> constexpr T& get(array<T, N>&) noexcept; template<size_t I, class T, size_t N> constexpr T&& get(array<T, N>&&) noexcept; template<size_t I, class T, size_t N> constexpr const T& get(const array<T, N>&) noexcept; template<size_t I, class T, size_t N> constexpr const T&& get(const array<T, N>&&) noexcept; } ``` #### Class template `[std::array](../container/array "cpp/container/array")` ``` namespace std { template<class T, size_t N> struct array { // types using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using size_type = size_t; using difference_type = ptrdiff_t; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // no explicit construct/copy/destroy for aggregate type constexpr void fill(const T& u); constexpr void swap(array&) noexcept(is_nothrow_swappable_v<T>); // iterators constexpr iterator begin() noexcept; constexpr const_iterator begin() const noexcept; constexpr iterator end() noexcept; constexpr const_iterator end() const noexcept; constexpr reverse_iterator rbegin() noexcept; constexpr const_reverse_iterator rbegin() const noexcept; constexpr reverse_iterator rend() noexcept; constexpr const_reverse_iterator rend() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept; constexpr const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] constexpr bool empty() const noexcept; constexpr size_type size() const noexcept; constexpr size_type max_size() const noexcept; // element access constexpr reference operator[](size_type n); constexpr const_reference operator[](size_type n) const; constexpr reference at(size_type n); constexpr const_reference at(size_type n) const; constexpr reference front(); constexpr const_reference front() const; constexpr reference back(); constexpr const_reference back() const; constexpr T * data() noexcept; constexpr const T * data() const noexcept; }; template<class T, class... U> array(T, U...) -> array<T, 1 + sizeof...(U)>; } ``` cpp Standard library header <memory> Standard library header <memory> ================================ This header is part of the [dynamic memory management](../memory "cpp/memory") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | Pointer traits | | [pointer\_traits](../memory/pointer_traits "cpp/memory/pointer traits") (C++11) | provides information about pointer-like types (class template) | | Garbage collector support | | [pointer\_safety](../memory/gc/pointer_safety "cpp/memory/gc/pointer safety") (C++11)(removed in C++23) | lists pointer safety models (enum) | | Allocators | | [allocator](../memory/allocator "cpp/memory/allocator") | the default allocator (class template) | | [allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits") (C++11) | provides information about allocator types (class template) | | [allocation\_result](../memory/allocation_result "cpp/memory/allocation result") (C++23) | records the address and the actual size of storage allocated by `allocate_at_least` (class template) | | [allocator\_arg\_t](../memory/allocator_arg_t "cpp/memory/allocator arg t") (C++11) | tag type used to select allocator-aware constructor overloads (class) | | [uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator") (C++11) | checks if the specified type supports uses-allocator construction (class template) | | Uninitialized storage | | [raw\_storage\_iterator](../memory/raw_storage_iterator "cpp/memory/raw storage iterator") (deprecated in C++17)(removed in C++20) | an iterator that allows standard algorithms to store results in uninitialized memory (class template) | | Smart pointers | | [unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr") (C++11) | smart pointer with unique object ownership semantics (class template) | | [shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr") (C++11) | smart pointer with shared object ownership semantics (class template) | | [weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr") (C++11) | weak reference to an object managed by `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (class template) | | [auto\_ptr](../memory/auto_ptr "cpp/memory/auto ptr") (deprecated in C++11)(removed in C++17) | smart pointer with strict object ownership semantics (class template) | | Helper classes | | [std::atomic<std::shared\_ptr>](../memory/shared_ptr/atomic2 "cpp/memory/shared ptr/atomic2") (C++20) | atomic shared pointer (class template specialization) | | [std::atomic<std::weak\_ptr>](../memory/weak_ptr/atomic2 "cpp/memory/weak ptr/atomic2") (C++20) | atomic weak pointer (class template specialization) | | [owner\_less](../memory/owner_less "cpp/memory/owner less") (C++11) | provides mixed-type owner-based ordering of shared and weak pointers (class template) | | [enable\_shared\_from\_this](../memory/enable_shared_from_this "cpp/memory/enable shared from this") (C++11) | allows an object to create a `shared_ptr` referring to itself (class template) | | [bad\_weak\_ptr](../memory/bad_weak_ptr "cpp/memory/bad weak ptr") (C++11) | exception thrown when accessing a `weak_ptr` which refers to already destroyed object (class) | | [default\_delete](../memory/default_delete "cpp/memory/default delete") (C++11) | default deleter for `[unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` (class template) | | [std::hash<std::unique\_ptr>](../memory/unique_ptr/hash "cpp/memory/unique ptr/hash") (C++11) | hash support for `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` (class template specialization) | | [std::hash<std::shared\_ptr>](../memory/shared_ptr/hash "cpp/memory/shared ptr/hash") (C++11) | hash support for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (class template specialization) | | Smart pointer adaptors | | [out\_ptr\_t](../memory/out_ptr_t "cpp/memory/out ptr t") (C++23) | interoperates with foreign pointer setters and resets a smart pointer on destruction (class template) | | [inout\_ptr\_t](../memory/inout_ptr_t "cpp/memory/inout ptr t") (C++23) | interoperates with foreign pointer setters, obtains the initial pointer value from a smart pointer, and resets it on destruction (class template) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Defined in header `[<atomic>](atomic "cpp/header/atomic")` | | [atomic](../atomic/atomic "cpp/atomic/atomic") (C++11) | atomic class template and specializations for bool, integral, and pointer types (class template) | | Constants | | [allocator\_arg](../memory/allocator_arg "cpp/memory/allocator arg") (C++11) | an object of type `[std::allocator\_arg\_t](../memory/allocator_arg_t "cpp/memory/allocator arg t")` used to select allocator-aware constructors (constant) | | Functions | | Allocators | | [allocate\_at\_least](../memory/allocate_at_least "cpp/memory/allocate at least") (C++23) | allocates storage at least as large as the requested size via an allocator (function template) | | Miscellaneous | | [to\_address](../memory/to_address "cpp/memory/to address") (C++20) | obtains a raw pointer from a pointer-like type (function template) | | [addressof](../memory/addressof "cpp/memory/addressof") (C++11) | obtains actual address of an object, even if the *&* operator is overloaded (function template) | | [align](../memory/align "cpp/memory/align") (C++11) | aligns a pointer in a buffer (function) | | [assume\_aligned](../memory/assume_aligned "cpp/memory/assume aligned") (C++20) | informs the compiler that a pointer is aligned (function template) | | Garbage collector support | | [declare\_reachable](../memory/gc/declare_reachable "cpp/memory/gc/declare reachable") (C++11)(removed in C++23) | declares that an object can not be recycled (function) | | [undeclare\_reachable](../memory/gc/undeclare_reachable "cpp/memory/gc/undeclare reachable") (C++11)(removed in C++23) | declares that an object can be recycled (function template) | | [declare\_no\_pointers](../memory/gc/declare_no_pointers "cpp/memory/gc/declare no pointers") (C++11)(removed in C++23) | declares that a memory area does not contain traceable pointers (function) | | [undeclare\_no\_pointers](../memory/gc/undeclare_no_pointers "cpp/memory/gc/undeclare no pointers") (C++11)(removed in C++23) | cancels the effect of `[std::declare\_no\_pointers](../memory/gc/declare_no_pointers "cpp/memory/gc/declare no pointers")` (function) | | [get\_pointer\_safety](../memory/gc/get_pointer_safety "cpp/memory/gc/get pointer safety") (C++11)(removed in C++23) | returns the current pointer safety model (function) | | Uninitialized storage | | [uninitialized\_copy](../memory/uninitialized_copy "cpp/memory/uninitialized copy") | copies a range of objects to an uninitialized area of memory (function template) | | [uninitialized\_copy\_n](../memory/uninitialized_copy_n "cpp/memory/uninitialized copy n") (C++11) | copies a number of objects to an uninitialized area of memory (function template) | | [uninitialized\_fill](../memory/uninitialized_fill "cpp/memory/uninitialized fill") | copies an object to an uninitialized area of memory, defined by a range (function template) | | [uninitialized\_fill\_n](../memory/uninitialized_fill_n "cpp/memory/uninitialized fill n") | copies an object to an uninitialized area of memory, defined by a start and a count (function template) | | [uninitialized\_move](../memory/uninitialized_move "cpp/memory/uninitialized move") (C++17) | moves a range of objects to an uninitialized area of memory (function template) | | [uninitialized\_move\_n](../memory/uninitialized_move_n "cpp/memory/uninitialized move n") (C++17) | moves a number of objects to an uninitialized area of memory (function template) | | [uninitialized\_default\_construct](../memory/uninitialized_default_construct "cpp/memory/uninitialized default construct") (C++17) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (function template) | | [uninitialized\_default\_construct\_n](../memory/uninitialized_default_construct_n "cpp/memory/uninitialized default construct n") (C++17) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and a count (function template) | | [uninitialized\_value\_construct](../memory/uninitialized_value_construct "cpp/memory/uninitialized value construct") (C++17) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (function template) | | [uninitialized\_value\_construct\_n](../memory/uninitialized_value_construct_n "cpp/memory/uninitialized value construct n") (C++17) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (function template) | | [construct\_at](../memory/construct_at "cpp/memory/construct at") (C++20) | creates an object at a given address (function template) | | [destroy\_at](../memory/destroy_at "cpp/memory/destroy at") (C++17) | destroys an object at a given address (function template) | | [destroy](../memory/destroy "cpp/memory/destroy") (C++17) | destroys a range of objects (function template) | | [destroy\_n](../memory/destroy_n "cpp/memory/destroy n") (C++17) | destroys a number of objects in a range (function template) | | [get\_temporary\_buffer](../memory/get_temporary_buffer "cpp/memory/get temporary buffer") (deprecated in C++17)(removed in C++20) | obtains uninitialized storage (function template) | | [return\_temporary\_buffer](../memory/return_temporary_buffer "cpp/memory/return temporary buffer") (deprecated in C++17)(removed in C++20) | frees uninitialized storage (function template) | | Smart pointer non-member operations | | [make\_uniquemake\_unique\_for\_overwrite](../memory/unique_ptr/make_unique "cpp/memory/unique ptr/make unique") (C++14)(C++20) | creates a unique pointer that manages a new object (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../memory/unique_ptr/operator_cmp "cpp/memory/unique ptr/operator cmp") (removed in C++20)(C++20) | compares to another `unique_ptr` or with `nullptr` (function template) | | [make\_sharedmake\_shared\_for\_overwrite](../memory/shared_ptr/make_shared "cpp/memory/shared ptr/make shared") (C++20) | creates a shared pointer that manages a new object (function template) | | [allocate\_sharedallocate\_shared\_for\_overwrite](../memory/shared_ptr/allocate_shared "cpp/memory/shared ptr/allocate shared") (C++20) | creates a shared pointer that manages a new object allocated using an allocator (function template) | | [static\_pointer\_castdynamic\_pointer\_castconst\_pointer\_castreinterpret\_pointer\_cast](../memory/shared_ptr/pointer_cast "cpp/memory/shared ptr/pointer cast") (C++17) | applies [`static_cast`](../language/static_cast "cpp/language/static cast"), [`dynamic_cast`](../language/dynamic_cast "cpp/language/dynamic cast"), [`const_cast`](../language/const_cast "cpp/language/const cast"), or [`reinterpret_cast`](../language/reinterpret_cast "cpp/language/reinterpret cast") to the stored pointer (function template) | | [get\_deleter](../memory/shared_ptr/get_deleter "cpp/memory/shared ptr/get deleter") | returns the deleter of specified type, if owned (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../memory/shared_ptr/operator_cmp "cpp/memory/shared ptr/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares with another `shared_ptr` or with `nullptr` (function template) | | [operator<<](../memory/shared_ptr/operator_ltlt "cpp/memory/shared ptr/operator ltlt") | outputs the value of the stored pointer to an output stream (function template) | | [std::swap(std::unique\_ptr)](../memory/unique_ptr/swap2 "cpp/memory/unique ptr/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::shared\_ptr)](../memory/shared_ptr/swap2 "cpp/memory/shared ptr/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [std::swap(std::weak\_ptr)](../memory/weak_ptr/swap2 "cpp/memory/weak ptr/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | Smart pointer adaptor creation | | [out\_ptr](../memory/out_ptr_t/out_ptr "cpp/memory/out ptr t/out ptr") (C++23) | creates an `out_ptr_t` with an associated smart pointer and resetting arguments (function template) | | [inout\_ptr](../memory/inout_ptr_t/inout_ptr "cpp/memory/inout ptr t/inout ptr") (C++23) | creates an `inout_ptr_t` with an associated smart pointer and resetting arguments (function template) | | | | | --- | --- | | [std::atomic\_is\_lock\_free(std::shared\_ptr)std::atomic\_load(std::shared\_ptr)std::atomic\_load\_explicit(std::shared\_ptr)std::atomic\_store(std::shared\_ptr)std::atomic\_store\_explicit(std::shared\_ptr)std::atomic\_exchange(std::shared\_ptr)std::atomic\_exchange\_explicit(std::shared\_ptr)std::atomic\_compare\_exchange\_weak(std::shared\_ptr)std::atomic\_compare\_exchange\_strong(std::shared\_ptr)std::atomic\_compare\_exchange\_weak\_explicit(std::shared\_ptr)std::atomic\_compare\_exchange\_strong\_explicit(std::shared\_ptr)](../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") (deprecated in C++20) | specializes atomic operations for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (function template) | | | | --- | | Function-like entities | | Defined in namespace `std::ranges` | | Uninitialized storage | | [ranges::uninitialized\_copy](../memory/ranges/uninitialized_copy "cpp/memory/ranges/uninitialized copy") (C++20) | copies a range of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_copy\_n](../memory/ranges/uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n") (C++20) | copies a number of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_fill](../memory/ranges/uninitialized_fill "cpp/memory/ranges/uninitialized fill") (C++20) | copies an object to an uninitialized area of memory, defined by a range (niebloid) | | [ranges::uninitialized\_fill\_n](../memory/ranges/uninitialized_fill_n "cpp/memory/ranges/uninitialized fill n") (C++20) | copies an object to an uninitialized area of memory, defined by a start and a count (niebloid) | | [ranges::uninitialized\_move](../memory/ranges/uninitialized_move "cpp/memory/ranges/uninitialized move") (C++20) | moves a range of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_move\_n](../memory/ranges/uninitialized_move_n "cpp/memory/ranges/uninitialized move n") (C++20) | moves a number of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_default\_construct](../memory/ranges/uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct") (C++20) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (niebloid) | | [ranges::uninitialized\_default\_construct\_n](../memory/ranges/uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n") (C++20) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and count (niebloid) | | [ranges::uninitialized\_value\_construct](../memory/ranges/uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct") (C++20) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (niebloid) | | [ranges::uninitialized\_value\_construct\_n](../memory/ranges/uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n") (C++20) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (niebloid) | | [ranges::construct\_at](../memory/ranges/construct_at "cpp/memory/ranges/construct at") (C++20) | creates an object at a given address (niebloid) | | [ranges::destroy\_at](../memory/ranges/destroy_at "cpp/memory/ranges/destroy at") (C++20) | destroys an object at a given address (niebloid) | | [ranges::destroy](../memory/ranges/destroy "cpp/memory/ranges/destroy") (C++20) | destroys a range of objects (niebloid) | | [ranges::destroy\_n](../memory/ranges/destroy_n "cpp/memory/ranges/destroy n") (C++20) | destroys a number of objects in a range (niebloid) | ### Synopsis ``` #include <compare> namespace std { // pointer traits template<class Ptr> struct pointer_traits; template<class T> struct pointer_traits<T*>; // pointer conversion template<class T> constexpr T* to_address(T* p) noexcept; template<class Ptr> constexpr auto to_address(const Ptr& p) noexcept; // pointer alignment void* align(size_t alignment, size_t size, void*& ptr, size_t& space); template<size_t N, class T> [[nodiscard]] constexpr T* assume_aligned(T* ptr); // allocator argument tag struct allocator_arg_t { explicit allocator_arg_t() = default; }; inline constexpr allocator_arg_t allocator_arg{}; // uses_allocator template<class T, class Alloc> struct uses_allocator; // uses_allocator template<class T, class Alloc> inline constexpr bool uses_allocator_v = uses_allocator<T, Alloc>::value; // uses-allocator construction template<class T, class Alloc, class... Args> constexpr auto uses_allocator_construction_args(const Alloc& alloc, Args&&... args) noexcept; template<class T, class Alloc, class Tuple1, class Tuple2> constexpr auto uses_allocator_construction_args(const Alloc& alloc, piecewise_construct_t, Tuple1&& x, Tuple2&& y) noexcept; template<class T, class Alloc> constexpr auto uses_allocator_construction_args(const Alloc& alloc) noexcept; template<class T, class Alloc, class U, class V> constexpr auto uses_allocator_construction_args(const Alloc& alloc, U&& u, V&& v) noexcept; template<class T, class Alloc, class U, class V> constexpr auto uses_allocator_construction_args(const Alloc& alloc, const pair<U, V>& pr) noexcept; template<class T, class Alloc, class U, class V> constexpr auto uses_allocator_construction_args(const Alloc& alloc, pair<U, V>&& pr) noexcept; template<class T, class Alloc, class... Args> constexpr T make_obj_using_allocator(const Alloc& alloc, Args&&... args); template<class T, class Alloc, class... Args> constexpr T* uninitialized_construct_using_allocator(T* p, const Alloc& alloc, Args&&... args); // allocator traits template<class Alloc> struct allocator_traits; template<class Pointer> struct allocation_result { Pointer ptr; size_t count; }; template<class Allocator> [[nodiscard]] constexpr allocation_result<typename allocator_traits<Allocator>::pointer> allocate_at_least(Allocator& a, size_t n); // the default allocator template<class T> class allocator; template<class T, class U> constexpr bool operator==(const allocator<T>&, const allocator<U>&) noexcept; // addressof template<class T> constexpr T* addressof(T& r) noexcept; template<class T> const T* addressof(const T&&) = delete; // specialized algorithms // special memory concepts template<class I> concept no-throw-input-iterator = /* see description */; // exposition only template<class I> concept no-throw-forward-iterator = /* see description */; // exposition only template<class S, class I> concept no-throw-sentinel-for = /* see description */; // exposition only template<class R> concept no-throw-input-range = /* see description */; // exposition only template<class R> concept no-throw-forward-range = /* see description */; // exposition only template<class NoThrowForwardIt> void uninitialized_default_construct(NoThrowForwardIt first, NoThrowForwardIt last); template<class ExecutionPolicy, class NoThrowForwardIt> void uninitialized_default_construct(ExecutionPolicy&& exec, NoThrowForwardIt first, NoThrowForwardIt last); template<class NoThrowForwardIt, class Size> NoThrowForwardIt uninitialized_default_construct_n(NoThrowForwardIt first, Size n); template<class ExecutionPolicy, class NoThrowForwardIt, class Size> NoThrowForwardIt uninitialized_default_construct_n(ExecutionPolicy&& exec, NoThrowForwardIt first, Size n); namespace ranges { template<no-throw-forward-iterator I, no-throw-sentinel-for<I> S> requires default_initializable<iter_value_t<I>> I uninitialized_default_construct(I first, S last); template<no-throw-forward-range R> requires default_initializable<range_value_t<R>> borrowed_iterator_t<R> uninitialized_default_construct(R&& r); template<no-throw-forward-iterator I> requires default_initializable<iter_value_t<I>> I uninitialized_default_construct_n(I first, iter_difference_t<I> n); } template<class NoThrowForwardIterator> void uninitialized_value_construct(NoThrowForwardIterator first, NoThrowForwardIterator last); template<class ExecutionPolicy, class NoThrowForwardIt> void uninitialized_value_construct(ExecutionPolicy&& exec, NoThrowForwardIt first, NoThrowForwardIt last); template<class NoThrowForwardIt, class Size> NoThrowForwardIt uninitialized_value_construct_n(NoThrowForwardIt first, Size n); template<class ExecutionPolicy, class NoThrowForwardIt, class Size> NoThrowForwardIt uninitialized_value_construct_n(ExecutionPolicy&& exec, NoThrowForwardIt first, Size n); namespace ranges { template<no-throw-forward-iterator I, no-throw-sentinel-for<I> S> requires default_initializable<iter_value_t<I>> I uninitialized_value_construct(I first, S last); template<no-throw-forward-range R> requires default_initializable<range_value_t<R>> borrowed_iterator_t<R> uninitialized_value_construct(R&& r); template<no-throw-forward-iterator I> requires default_initializable<iter_value_t<I>> I uninitialized_value_construct_n(I first, iter_difference_t<I> n); } template<class InputIt, class NoThrowForwardIt> NoThrowForwardIt uninitialized_copy(InputIt first, InputIt last, NoThrowForwardIt result); template<class ExecutionPolicy, class ForwardIt, class NoThrowForwardIt> NoThrowForwardIt uninitialized_copy(ExecutionPolicy&& exec, ForwardIt first, ForwardIt last, NoThrowForwardIt result); template<class InputIt, class Size, class NoThrowForwardIt> NoThrowForwardIt uninitialized_copy_n(InputIt first, Size n, NoThrowForwardIt result); template<class ExecutionPolicy, class ForwardIt, class Size, class NoThrowForwardIt> NoThrowForwardIt uninitialized_copy_n(ExecutionPolicy&& exec, ForwardIt first, Size n, NoThrowForwardIt result); namespace ranges { template<class I, class O> using uninitialized_copy_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S1, no-throw-forward-iterator O, no-throw-sentinel-for<O> S2> requires constructible_from<iter_value_t<O>, iter_reference_t<I>> uninitialized_copy_result<I, O> uninitialized_copy(I ifirst, S1 ilast, O ofirst, S2 olast); template<input_range IR, no-throw-forward-range OR> requires constructible_from<range_value_t<OR>, range_reference_t<IR>> uninitialized_copy_result<borrowed_iterator_t<IR>, borrowed_iterator_t<OR>> uninitialized_copy(IR&& in_range, OR&& out_range); template<class I, class O> using uninitialized_copy_n_result = in_out_result<I, O>; template<input_iterator I, no-throw-forward-iterator O, no-throw-sentinel-for<O> S> requires constructible_from<iter_value_t<O>, iter_reference_t<I>> uninitialized_copy_n_result<I, O> uninitialized_copy_n(I ifirst, iter_difference_t<I> n, O ofirst, S olast); } template<class InputIt, class NoThrowForwardIt> NoThrowForwardIt uninitialized_move(InputIt first, InputIt last, NoThrowForwardIt result); template<class ExecutionPolicy, class ForwardIt, class NoThrowForwardIt> NoThrowForwardIt uninitialized_move(ExecutionPolicy&& exec, ForwardIt first, ForwardIt last, NoThrowForwardIt result); template<class InputIt, class Size, class NoThrowForwardIt> pair<InputIt, NoThrowForwardIt> uninitialized_move_n(InputIt first, Size n, NoThrowForwardIt result); template<class ExecutionPolicy, class ForwardIt, class Size, class NoThrowForwardIt> pair<ForwardIt, NoThrowForwardIt> uninitialized_move_n(ExecutionPolicy&& exec, ForwardIt first, Size n, NoThrowForwardIt result); namespace ranges { template<class I, class O> using uninitialized_move_result = in_out_result<I, O>; template<input_iterator I, sentinel_for<I> S1, no-throw-forward-iterator O, no-throw-sentinel-for<O> S2> requires constructible_from<iter_value_t<O>, iter_rvalue_reference_t<I>> uninitialized_move_result<I, O> uninitialized_move(I ifirst, S1 ilast, O ofirst, S2 olast); template<input_range IR, no-throw-forward-range OR> requires constructible_from<range_value_t<OR>, range_rvalue_reference_t<IR>> uninitialized_move_result<borrowed_iterator_t<IR>, borrowed_iterator_t<OR>> uninitialized_move(IR&& in_range, OR&& out_range); template<class I, class O> using uninitialized_move_n_result = in_out_result<I, O>; template<input_iterator I, no-throw-forward-iterator O, no-throw-sentinel-for<O> S> requires constructible_from<iter_value_t<O>, iter_rvalue_reference_t<I>> uninitialized_move_n_result<I, O> uninitialized_move_n(I ifirst, iter_difference_t<I> n, O ofirst, S olast); } template<class NoThrowForwardIt, class T> void uninitialized_fill(NoThrowForwardIt first, NoThrowForwardIt last, const T& x); template<class ExecutionPolicy, class NoThrowForwardIt, class T> void uninitialized_fill(ExecutionPolicy&& exec, NoThrowForwardIt first, NoThrowForwardIt last, const T& x); template<class NoThrowForwardIt, class Size, class T> NoThrowForwardIt uninitialized_fill_n(NoThrowForwardIt first, Size n, const T& x); template<class ExecutionPolicy, class NoThrowForwardIt, class Size, class T> NoThrowForwardIt uninitialized_fill_n(ExecutionPolicy&& exec, NoThrowForwardIt first, Size n, const T& x); namespace ranges { template<no-throw-forward-iterator I, no-throw-sentinel-for<I> S, class T> requires constructible_from<iter_value_t<I>, const T&> I uninitialized_fill(I first, S last, const T& x); template<no-throw-forward-range R, class T> requires constructible_from<range_value_t<R>, const T&> borrowed_iterator_t<R> uninitialized_fill(R&& r, const T& x); template<no-throw-forward-iterator I, class T> requires constructible_from<iter_value_t<I>, const T&> I uninitialized_fill_n(I first, iter_difference_t<I> n, const T& x); } // construct_at template<class T, class... Args> constexpr T* construct_at(T* location, Args&&... args); namespace ranges { template<class T, class... Args> constexpr T* construct_at(T* location, Args&&... args); } // destroy template<class T> constexpr void destroy_at(T* location); template<class NoThrowForwardIt> constexpr void destroy(NoThrowForwardIt first, NoThrowForwardIt last); template<class ExecutionPolicy, class NoThrowForwardIt> void destroy(ExecutionPolicy&& exec, NoThrowForwardIt first, NoThrowForwardIt last); template<class NoThrowForwardIt, class Size> constexpr NoThrowForwardIt destroy_n(NoThrowForwardIt first, Size n); template<class ExecutionPolicy, class NoThrowForwardIt, class Size> NoThrowForwardIt destroy_n(ExecutionPolicy&& exec, NoThrowForwardIt first, Size n); namespace ranges { template<destructible T> constexpr void destroy_at(T* location) noexcept; template<no-throw-input-iterator I, no-throw-sentinel-for<I> S> requires destructible<iter_value_t<I>> constexpr I destroy(I first, S last) noexcept; template<no-throw-input-range R> requires destructible<range_value_t<R>> constexpr borrowed_iterator_t<R> destroy(R&& r) noexcept; template<no-throw-input-iterator I> requires destructible<iter_value_t<I>> constexpr I destroy_n(I first, iter_difference_t<I> n) noexcept; } // class template unique_ptr template<class T> struct default_delete; template<class T> struct default_delete<T[]>; template<class T, class D = default_delete<T>> class unique_ptr; template<class T, class D> class unique_ptr<T[], D>; template<class T, class... Args> unique_ptr<T> make_unique(Args&&... args); // T is not array template<class T> unique_ptr<T> make_unique(size_t n); // T is U[] template<class T, class... Args> /* unspecified */ make_unique(Args&&...) = delete; // T is U[N] template<class T> unique_ptr<T> make_unique_for_overwrite(); // T is not array template<class T> unique_ptr<T> make_unique_for_overwrite(size_t n); // T is U[] template<class T, class... Args> /* unspecified */ make_unique_for_overwrite(Args&&...) = delete; // T is U[N] template<class T, class D> void swap(unique_ptr<T, D>& x, unique_ptr<T, D>& y) noexcept; template<class T1, class D1, class T2, class D2> bool operator==(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template<class T1, class D1, class T2, class D2> bool operator<(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template<class T1, class D1, class T2, class D2> bool operator>(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template<class T1, class D1, class T2, class D2> bool operator<=(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template<class T1, class D1, class T2, class D2> bool operator>=(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template<class T1, class D1, class T2, class D2> requires three_way_comparable_with<typename unique_ptr<T1, D1>::pointer, typename unique_ptr<T2, D2>::pointer> compare_three_way_result_t<typename unique_ptr<T1, D1>::pointer, typename unique_ptr<T2, D2>::pointer> operator<=>(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template<class T, class D> bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept; template<class T, class D> bool operator<(const unique_ptr<T, D>& x, nullptr_t); template<class T, class D> bool operator<(nullptr_t, const unique_ptr<T, D>& y); template<class T, class D> bool operator>(const unique_ptr<T, D>& x, nullptr_t); template<class T, class D> bool operator>(nullptr_t, const unique_ptr<T, D>& y); template<class T, class D> bool operator<=(const unique_ptr<T, D>& x, nullptr_t); template<class T, class D> bool operator<=(nullptr_t, const unique_ptr<T, D>& y); template<class T, class D> bool operator>=(const unique_ptr<T, D>& x, nullptr_t); template<class T, class D> bool operator>=(nullptr_t, const unique_ptr<T, D>& y); template<class T, class D> requires three_way_comparable<typename unique_ptr<T, D>::pointer> compare_three_way_result_t<typename unique_ptr<T, D>::pointer> operator<=>(const unique_ptr<T, D>& x, nullptr_t); template<class E, class T, class Y, class D> basic_ostream<E, T>& operator<<(basic_ostream<E, T>& os, const unique_ptr<Y, D>& p); // class bad_weak_ptr class bad_weak_ptr; // class template shared_ptr template<class T> class shared_ptr; // shared_ptr creation template<class T, class... Args> shared_ptr<T> make_shared(Args&&... args); // T is not array template<class T, class A, class... Args> shared_ptr<T> allocate_shared(const A& a, Args&&... args); // T is not array template<class T> shared_ptr<T> make_shared(size_t N); // T is U[] template<class T, class A> shared_ptr<T> allocate_shared(const A& a, size_t N); // T is U[] template<class T> shared_ptr<T> make_shared(); // T is U[N] template<class T, class A> shared_ptr<T> allocate_shared(const A& a); // T is U[N] template<class T> shared_ptr<T> make_shared(size_t N, const remove_extent_t<T>& u); // T is U[] template<class T, class A> shared_ptr<T> allocate_shared(const A& a, size_t N, const remove_extent_t<T>& u); // T is U[] template<class T> shared_ptr<T> make_shared(const remove_extent_t<T>& u); // T is U[N] template<class T, class A> shared_ptr<T> allocate_shared(const A& a, const remove_extent_t<T>& u); // T is U[N] template<class T> shared_ptr<T> make_shared_for_overwrite(); // T is not U[] template<class T, class A> shared_ptr<T> allocate_shared_for_overwrite(const A& a); // T is not U[] template<class T> shared_ptr<T> make_shared_for_overwrite(size_t N); // T is U[] template<class T, class A> shared_ptr<T> allocate_shared_for_overwrite(const A& a, size_t N); // T is U[] // shared_ptr comparisons template<class T, class U> bool operator==(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept; template<class T, class U> strong_ordering operator<=>(const shared_ptr<T>& a, const shared_ptr<U>& b) noexcept; template<class T> bool operator==(const shared_ptr<T>& x, nullptr_t) noexcept; template<class T> strong_ordering operator<=>(const shared_ptr<T>& x, nullptr_t) noexcept; // shared_ptr specialized algorithms template<class T> void swap(shared_ptr<T>& a, shared_ptr<T>& b) noexcept; // shared_ptr casts template<class T, class U> shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r) noexcept; template<class T, class U> shared_ptr<T> static_pointer_cast(shared_ptr<U>&& r) noexcept; template<class T, class U> shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r) noexcept; template<class T, class U> shared_ptr<T> dynamic_pointer_cast(shared_ptr<U>&& r) noexcept; template<class T, class U> shared_ptr<T> const_pointer_cast(const shared_ptr<U>& r) noexcept; template<class T, class U> shared_ptr<T> const_pointer_cast(shared_ptr<U>&& r) noexcept; template<class T, class U> shared_ptr<T> reinterpret_pointer_cast(const shared_ptr<U>& r) noexcept; template<class T, class U> shared_ptr<T> reinterpret_pointer_cast(shared_ptr<U>&& r) noexcept; // shared_ptr get_deleter template<class D, class T> D* get_deleter(const shared_ptr<T>& p) noexcept; // shared_ptr I/O template<class E, class T, class Y> basic_ostream<E, T>& operator<<(basic_ostream<E, T>& os, const shared_ptr<Y>& p); // class template weak_ptr template<class T> class weak_ptr; // weak_ptr specialized algorithms template<class T> void swap(weak_ptr<T>& a, weak_ptr<T>& b) noexcept; // class template owner_less template<class T = void> struct owner_less; // class template enable_shared_from_this template<class T> class enable_shared_from_this; // hash support template<class T> struct hash; template<class T, class D> struct hash<unique_ptr<T, D>>; template<class T> struct hash<shared_ptr<T>>; // atomic smart pointers template<class T> struct atomic; template<class T> struct atomic<shared_ptr<T>>; template<class T> struct atomic<weak_ptr<T>>; // class template out_ptr_t template<class Smart, class Pointer, class... Args> class out_ptr_t; // function template out_ptr template<class Pointer = void, class Smart, class... Args> auto out_ptr(Smart& s, Args&&... args); // class template inout_ptr_t template<class Smart, class Pointer, class... Args> class inout_ptr_t; // function template inout_ptr template<class Pointer = void, class Smart, class... Args> auto inout_ptr(Smart& s, Args&&... args); } // deprecated namespace std { template<class T> bool atomic_is_lock_free(const shared_ptr<T>* p); template<class T> shared_ptr<T> atomic_load(const shared_ptr<T>* p); template<class T> shared_ptr<T> atomic_load_explicit(const shared_ptr<T>* p, memory_order mo); template<class T> void atomic_store(shared_ptr<T>* p, shared_ptr<T> r); template<class T> void atomic_store_explicit(shared_ptr<T>* p, shared_ptr<T> r, memory_order mo); template<class T> shared_ptr<T> atomic_exchange(shared_ptr<T>* p, shared_ptr<T> r); template<class T> shared_ptr<T> atomic_exchange_explicit(shared_ptr<T>* p, shared_ptr<T> r, memory_order mo); template<class T> bool atomic_compare_exchange_weak(shared_ptr<T>* p, shared_ptr<T>* v, shared_ptr<T> w); template<class T> bool atomic_compare_exchange_strong(shared_ptr<T>* p, shared_ptr<T>* v, shared_ptr<T> w); template<class T> bool atomic_compare_exchange_weak_explicit( shared_ptr<T>* p, shared_ptr<T>* v, shared_ptr<T> w, memory_order success, memory_order failure); template<class T> bool atomic_compare_exchange_strong_explicit( shared_ptr<T>* p, shared_ptr<T>* v, shared_ptr<T> w, memory_order success, memory_order failure); } ``` #### Helper concepts ``` template<class I> concept no-throw-input-iterator = // exposition only input_iterator<I> && is_lvalue_reference_v<iter_reference_t<I>> && same_as<remove_cvref_t<iter_reference_t<I>>, iter_value_t<I>>; template<class S, class I> concept no-throw-sentinel-for = sentinel_for<S, I>; // exposition only template<class R> concept no-throw-input-range = // exposition only ranges::range<R> && no-throw-input-iterator<ranges::iterator_t<R>> && no-throw-sentinel-for<ranges::sentinel_t<R>, ranges::iterator_t<R>>; template<class I> concept no-throw-forward-iterator = // exposition only no-throw-input-iterator<I> && forward_iterator<I> && no-throw-sentinel-for<I, I>; template<class R> concept no-throw-forward-range = // exposition only no-throw-input-range<R> && no-throw-forward-iterator<ranges::iterator_t<R>>; ``` Note: [These names](../memory/ranges/nothrow_concepts "cpp/memory/ranges/nothrow concepts") are only for exposition, they are not part of the interface. #### Class template `[std::pointer\_traits](../memory/pointer_traits "cpp/memory/pointer traits")` ``` namespace std { template<class Ptr> struct pointer_traits { using pointer = Ptr; using element_type = /* see description */; using difference_type = /* see description */; template<class U> using rebind = /* see description */; static pointer pointer_to(/* see description */ r); }; template<class T> struct pointer_traits<T*> { using pointer = T*; using element_type = T; using difference_type = ptrdiff_t; template<class U> using rebind = U*; static constexpr pointer pointer_to(/* see description */ r) noexcept; }; } ``` #### Class `[std::allocator\_arg\_t](../memory/allocator_arg_t "cpp/memory/allocator arg t")` ``` namespace std { struct allocator_arg_t { explicit allocator_arg_t() = default; }; inline constexpr allocator_arg_t allocator_arg{}; } ``` #### Class template `[std::allocator\_traits](../memory/allocator_traits "cpp/memory/allocator traits")` ``` namespace std { template<class Alloc> struct allocator_traits { using allocator_type = Alloc; using value_type = typename Alloc::value_type; using pointer = /* see description */; using const_pointer = /* see description */; using void_pointer = /* see description */; using const_void_pointer = /* see description */; using difference_type = /* see description */; using size_type = /* see description */; using propagate_on_container_copy_assignment = /* see description */; using propagate_on_container_move_assignment = /* see description */; using propagate_on_container_swap = /* see description */; using is_always_equal = /* see description */; template<class T> using rebind_alloc = /* see description */; template<class T> using rebind_traits = allocator_traits<rebind_alloc<T>>; [[nodiscard]] static pointer allocate(Alloc& a, size_type n); [[nodiscard]] static pointer allocate(Alloc& a, size_type n, const_void_pointer hint); static void deallocate(Alloc& a, pointer p, size_type n); template<class T, class... Args> static void construct(Alloc& a, T* p, Args&&... args); template<class T> static void destroy(Alloc& a, T* p); static size_type max_size(const Alloc& a) noexcept; static Alloc select_on_container_copy_construction(const Alloc& rhs); }; } ``` #### Class template `[std::allocator](../memory/allocator "cpp/memory/allocator")` ``` namespace std { template<class T> class allocator { public: using value_type = T; using size_type = size_t; using difference_type = ptrdiff_t; using propagate_on_container_move_assignment = true_type; constexpr allocator() noexcept; constexpr allocator(const allocator&) noexcept; template<class U> constexpr allocator(const allocator<U>&) noexcept; constexpr ~allocator(); constexpr allocator& operator=(const allocator&) = default; [[nodiscard]] constexpr T* allocate(size_t n); [[nodiscard]] constexpr allocation_result<T*> allocate_at_least(size_t n); constexpr void deallocate(T* p, size_t n); // deprecated using is_always_equal = true_type; }; } ``` #### Class template `[std::default\_delete](../memory/default_delete "cpp/memory/default delete")` ``` namespace std { template<class T> struct default_delete { constexpr default_delete() noexcept = default; template<class U> default_delete(const default_delete<U>&) noexcept; void operator()(T*) const; }; template<class T> struct default_delete<T[]> { constexpr default_delete() noexcept = default; template<class U> default_delete(const default_delete<U[]>&) noexcept; template<class U> void operator()(U* ptr) const; }; } ``` #### Class template `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` ``` namespace std { template<class T, class D = default_delete<T>> class unique_ptr { public: using pointer = /* see description */; using element_type = T; using deleter_type = D; // constructors constexpr unique_ptr() noexcept; explicit unique_ptr(pointer p) noexcept; unique_ptr(pointer p, /* see description */ d1) noexcept; unique_ptr(pointer p, /* see description */ d2) noexcept; unique_ptr(unique_ptr&& u) noexcept; constexpr unique_ptr(nullptr_t) noexcept; template<class U, class E> unique_ptr(unique_ptr<U, E>&& u) noexcept; // destructor ~unique_ptr(); // assignment unique_ptr& operator=(unique_ptr&& u) noexcept; template<class U, class E> unique_ptr& operator=(unique_ptr<U, E>&& u) noexcept; unique_ptr& operator=(nullptr_t) noexcept; // observers add_lvalue_reference_t<T> operator*() const noexcept(/* see description */); pointer operator->() const noexcept; pointer get() const noexcept; deleter_type& get_deleter() noexcept; const deleter_type& get_deleter() const noexcept; explicit operator bool() const noexcept; // modifiers pointer release() noexcept; void reset(pointer p = pointer()) noexcept; void swap(unique_ptr& u) noexcept; // disable copy from lvalue unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; template<class T, class D> class unique_ptr<T[], D> { public: using pointer = /* see description */; using element_type = T; using deleter_type = D; // constructors constexpr unique_ptr() noexcept; template<class U> explicit unique_ptr(U p) noexcept; template<class U> unique_ptr(U p, /* see description */ d) noexcept; template<class U> unique_ptr(U p, /* see description */ d) noexcept; unique_ptr(unique_ptr&& u) noexcept; template<class U, class E> unique_ptr(unique_ptr<U, E>&& u) noexcept; constexpr unique_ptr(nullptr_t) noexcept; // destructor ~unique_ptr(); // assignment unique_ptr& operator=(unique_ptr&& u) noexcept; template<class U, class E> unique_ptr& operator=(unique_ptr<U, E>&& u) noexcept; unique_ptr& operator=(nullptr_t) noexcept; // observers T& operator[](size_t i) const; pointer get() const noexcept; deleter_type& get_deleter() noexcept; const deleter_type& get_deleter() const noexcept; explicit operator bool() const noexcept; // modifiers pointer release() noexcept; template<class U> void reset(U p) noexcept; void reset(nullptr_t = nullptr) noexcept; void swap(unique_ptr& u) noexcept; // disable copy from lvalue unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; } ``` #### Class `[std::bad\_weak\_ptr](../memory/bad_weak_ptr "cpp/memory/bad weak ptr")` ``` namespace std { class bad_weak_ptr : public exception { public: bad_weak_ptr() noexcept; }; } ``` #### Class template `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` ``` namespace std { template<class T> class shared_ptr { public: using element_type = remove_extent_t<T>; using weak_type = weak_ptr<T>; // constructors constexpr shared_ptr() noexcept; constexpr shared_ptr(nullptr_t) noexcept : shared_ptr() { } template<class Y> explicit shared_ptr(Y* p); template<class Y, class D> shared_ptr(Y* p, D d); template<class Y, class D, class A> shared_ptr(Y* p, D d, A a); template<class D> shared_ptr(nullptr_t p, D d); template<class D, class A> shared_ptr(nullptr_t p, D d, A a); template<class Y> shared_ptr(const shared_ptr<Y>& r, element_type* p) noexcept; template<class Y> shared_ptr(shared_ptr<Y>&& r, element_type* p) noexcept; shared_ptr(const shared_ptr& r) noexcept; template<class Y> shared_ptr(const shared_ptr<Y>& r) noexcept; shared_ptr(shared_ptr&& r) noexcept; template<class Y> shared_ptr(shared_ptr<Y>&& r) noexcept; template<class Y> explicit shared_ptr(const weak_ptr<Y>& r); template<class Y, class D> shared_ptr(unique_ptr<Y, D>&& r); // destructor ~shared_ptr(); // assignment shared_ptr& operator=(const shared_ptr& r) noexcept; template<class Y> shared_ptr& operator=(const shared_ptr<Y>& r) noexcept; shared_ptr& operator=(shared_ptr&& r) noexcept; template<class Y> shared_ptr& operator=(shared_ptr<Y>&& r) noexcept; template<class Y, class D> shared_ptr& operator=(unique_ptr<Y, D>&& r); // modifiers void swap(shared_ptr& r) noexcept; void reset() noexcept; template<class Y> void reset(Y* p); template<class Y, class D> void reset(Y* p, D d); template<class Y, class D, class A> void reset(Y* p, D d, A a); // observers element_type* get() const noexcept; T& operator*() const noexcept; T* operator->() const noexcept; element_type& operator[](ptrdiff_t i) const; long use_count() const noexcept; explicit operator bool() const noexcept; template<class U> bool owner_before(const shared_ptr<U>& b) const noexcept; template<class U> bool owner_before(const weak_ptr<U>& b) const noexcept; }; template<class T> shared_ptr(weak_ptr<T>) -> shared_ptr<T>; template<class T, class D> shared_ptr(unique_ptr<T, D>) -> shared_ptr<T>; } ``` #### Class template `[std::weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr")` ``` namespace std { template<class T> class weak_ptr { public: using element_type = remove_extent_t<T>; // constructors constexpr weak_ptr() noexcept; template<class Y> weak_ptr(const shared_ptr<Y>& r) noexcept; weak_ptr(const weak_ptr& r) noexcept; template<class Y> weak_ptr(const weak_ptr<Y>& r) noexcept; weak_ptr(weak_ptr&& r) noexcept; template<class Y> weak_ptr(weak_ptr<Y>&& r) noexcept; // destructor ~weak_ptr(); // assignment weak_ptr& operator=(const weak_ptr& r) noexcept; template<class Y> weak_ptr& operator=(const weak_ptr<Y>& r) noexcept; template<class Y> weak_ptr& operator=(const shared_ptr<Y>& r) noexcept; weak_ptr& operator=(weak_ptr&& r) noexcept; template<class Y> weak_ptr& operator=(weak_ptr<Y>&& r) noexcept; // modifiers void swap(weak_ptr& r) noexcept; void reset() noexcept; // observers long use_count() const noexcept; bool expired() const noexcept; shared_ptr<T> lock() const noexcept; template<class U> bool owner_before(const shared_ptr<U>& b) const noexcept; template<class U> bool owner_before(const weak_ptr<U>& b) const noexcept; }; template<class T> weak_ptr(shared_ptr<T>) -> weak_ptr<T>; } ``` #### Class template `[std::owner\_less](../memory/owner_less "cpp/memory/owner less")` ``` namespace std { template<class T = void> struct owner_less; template<class T> struct owner_less<shared_ptr<T>> { bool operator()(const shared_ptr<T>&, const shared_ptr<T>&) const noexcept; bool operator()(const shared_ptr<T>&, const weak_ptr<T>&) const noexcept; bool operator()(const weak_ptr<T>&, const shared_ptr<T>&) const noexcept; }; template<class T> struct owner_less<weak_ptr<T>> { bool operator()(const weak_ptr<T>&, const weak_ptr<T>&) const noexcept; bool operator()(const shared_ptr<T>&, const weak_ptr<T>&) const noexcept; bool operator()(const weak_ptr<T>&, const shared_ptr<T>&) const noexcept; }; template<> struct owner_less<void> { template<class T, class U> bool operator()(const shared_ptr<T>&, const shared_ptr<U>&) const noexcept; template<class T, class U> bool operator()(const shared_ptr<T>&, const weak_ptr<U>&) const noexcept; template<class T, class U> bool operator()(const weak_ptr<T>&, const shared_ptr<U>&) const noexcept; template<class T, class U> bool operator()(const weak_ptr<T>&, const weak_ptr<U>&) const noexcept; using is_transparent = /* unspecified */; }; } ``` #### Class template `[std::enable\_shared\_from\_this](../memory/enable_shared_from_this "cpp/memory/enable shared from this")` ``` namespace std { template<class T> class enable_shared_from_this { protected: constexpr enable_shared_from_this() noexcept; enable_shared_from_this(const enable_shared_from_this&) noexcept; enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept; ~enable_shared_from_this(); public: shared_ptr<T> shared_from_this(); shared_ptr<T const> shared_from_this() const; weak_ptr<T> weak_from_this() noexcept; weak_ptr<T const> weak_from_this() const noexcept; private: mutable weak_ptr<T> weak_this; // exposition only }; } ``` #### Class template `[std::atomic](../atomic/atomic "cpp/atomic/atomic")`'s specialization for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` ``` namespace std { template<class T> struct atomic<shared_ptr<T>> { using value_type = shared_ptr<T>; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const noexcept; void store(shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; shared_ptr<T> load(memory_order order = memory_order::seq_cst) const noexcept; operator shared_ptr<T>() const noexcept; shared_ptr<T> exchange(shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; bool compare_exchange_weak(shared_ptr<T>& expected, shared_ptr<T> desired, memory_order success, memory_order failure) noexcept; bool compare_exchange_strong(shared_ptr<T>& expected, shared_ptr<T> desired, memory_order success, memory_order failure) noexcept; bool compare_exchange_weak(shared_ptr<T>& expected, shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; bool compare_exchange_strong(shared_ptr<T>& expected, shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; constexpr atomic() noexcept = default; atomic(shared_ptr<T> desired) noexcept; atomic(const atomic&) = delete; void operator=(const atomic&) = delete; void operator=(shared_ptr<T> desired) noexcept; private: shared_ptr<T> p; // exposition only }; } ``` #### Class template `[std::atomic](../atomic/atomic "cpp/atomic/atomic")`'s specialization for `[std::weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr")` ``` namespace std { template<class T> struct atomic<weak_ptr<T>> { using value_type = weak_ptr<T>; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const noexcept; void store(weak_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; weak_ptr<T> load(memory_order order = memory_order::seq_cst) const noexcept; operator weak_ptr<T>() const noexcept; weak_ptr<T> exchange(weak_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; bool compare_exchange_weak(weak_ptr<T>& expected, weak_ptr<T> desired, memory_order success, memory_order failure) noexcept; bool compare_exchange_strong(weak_ptr<T>& expected, weak_ptr<T> desired, memory_order success, memory_order failure) noexcept; bool compare_exchange_weak(weak_ptr<T>& expected, weak_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; bool compare_exchange_strong(weak_ptr<T>& expected, weak_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept; constexpr atomic() noexcept = default; atomic(weak_ptr<T> desired) noexcept; atomic(const atomic&) = delete; void operator=(const atomic&) = delete; void operator=(weak_ptr<T> desired) noexcept; private: weak_ptr<T> p; // exposition only }; } ``` #### Class template `std::out_ptr_t` ``` namespace std { template<class Smart, class Pointer, class... Args> class out_ptr_t { public: explicit out_ptr_t(Smart&, Args...); out_ptr_t(const out_ptr_t&) = delete; ~out_ptr_t(); operator Pointer*() const noexcept; operator void**() const noexcept; private: Smart& s; // exposition only tuple<Args...> a; // exposition only Pointer p; // exposition only }; } ``` #### Class template `std::in_out_ptr_t` ``` namespace std { template<class Smart, class Pointer, class... Args> class inout_ptr_t { public: explicit inout_ptr_t(Smart&, Args...); inout_ptr_t(const inout_ptr_t&) = delete; ~inout_ptr_t(); operator Pointer*() const noexcept; operator void**() const noexcept; private: Smart& s; // exposition only tuple<Args...> a; // exposition only Pointer p; // exposition only }; } ```
programming_docs
cpp Standard library header <clocale> Standard library header <clocale> ================================= This header was originally in the C standard library as `<locale.h>`. This header is part of the [localization](../locale "cpp/locale") library. | | | --- | | Types | | [lconv](../locale/lconv "cpp/locale/lconv") | formatting details, returned by `[std::localeconv](../locale/localeconv "cpp/locale/localeconv")` (class) | | Constants | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | [LC\_ALLLC\_COLLATELC\_CTYPELC\_MONETARYLC\_NUMERICLC\_TIME](../locale/lc_categories "cpp/locale/LC categories") | locale categories for `[std::setlocale](../locale/setlocale "cpp/locale/setlocale")` (macro constant) | | Functions | | [setlocale](../locale/setlocale "cpp/locale/setlocale") | gets and sets the current C locale (function) | | [localeconv](../locale/localeconv "cpp/locale/localeconv") | queries numeric and monetary formatting details of the current locale (function) | ### Synopsis ``` namespace std { struct lconv; char* setlocale(int category, const char* locale); lconv* localeconv(); } #define NULL /* see description */ #define LC_ALL /* see description */ #define LC_COLLATE /* see description */ #define LC_CTYPE /* see description */ #define LC_MONETARY /* see description */ #define LC_NUMERIC /* see description */ #define LC_TIME /* see description */ ``` ### Notes * `[NULL](../types/null "cpp/types/NULL")` is also defined in the following headers: + [`<cstring>`](cstring "cpp/header/cstring") + [`<ctime>`](ctime "cpp/header/ctime") + [`<cstddef>`](cstddef "cpp/header/cstddef") + [`<cstdio>`](cstdio "cpp/header/cstdio") + [`<cwchar>`](cwchar "cpp/header/cwchar") cpp Standard library header <atomic> (C++11) Standard library header <atomic> (C++11) ======================================== This header is part of the [concurrency support](../thread "cpp/thread") library. | | | --- | | Classes | | [atomic](../atomic/atomic "cpp/atomic/atomic") (C++11) | atomic class template and specializations for bool, integral, and pointer types (class template) | | [atomic\_ref](../atomic/atomic_ref "cpp/atomic/atomic ref") (C++20) | provides atomic operations on non-atomic objects (class template) | | [atomic\_flag](../atomic/atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [memory\_order](../atomic/memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [atomic\_bool](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<bool>` (typedef) | | [atomic\_char](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char>` (typedef) | | [atomic\_schar](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<signed char>` (typedef) | | [atomic\_uchar](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned char>` (typedef) | | [atomic\_short](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<short>` (typedef) | | [atomic\_ushort](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned short>` (typedef) | | [atomic\_int](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<int>` (typedef) | | [atomic\_uint](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned int>` (typedef) | | [atomic\_long](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<long>` (typedef) | | [atomic\_ulong](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned long>` (typedef) | | [atomic\_llong](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<long long>` (typedef) | | [atomic\_ullong](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<unsigned long long>` (typedef) | | [atomic\_char8\_t](../atomic/atomic "cpp/atomic/atomic") (C++20) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char8_t>` (typedef) | | [atomic\_char16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char16\_t>` (typedef) | | [atomic\_char32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<char32\_t>` (typedef) | | [atomic\_wchar\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<wchar\_t>` (typedef) | | [atomic\_int8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_least64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_least64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_least64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_least64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast8\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast16\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast32\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_int\_fast64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::int\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uint\_fast64\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_intptr\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::intptr\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uintptr\_t](../atomic/atomic "cpp/atomic/atomic") (C++11)(optional) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uintptr\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_size\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>` (typedef) | | [atomic\_ptrdiff\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)>` (typedef) | | [atomic\_intmax\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::intmax\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_uintmax\_t](../atomic/atomic "cpp/atomic/atomic") (C++11) | `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | [atomic\_signed\_lock\_free](../atomic/atomic "cpp/atomic/atomic") (C++20) | a signed integral atomic type that is lock-free and for which waiting/notifying is most efficient (typedef) | | [atomic\_unsigned\_lock\_free](../atomic/atomic "cpp/atomic/atomic") (C++20) | a unsigned integral atomic type that is lock-free and for which waiting/notifying is most efficient (typedef) | | Functions | | [atomic\_is\_lock\_free](../atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") (C++11) | checks if the atomic type's operations are lock-free (function template) | | [atomic\_storeatomic\_store\_explicit](../atomic/atomic_store "cpp/atomic/atomic store") (C++11)(C++11) | atomically replaces the value of the atomic object with a non-atomic argument (function template) | | [atomic\_loadatomic\_load\_explicit](../atomic/atomic_load "cpp/atomic/atomic load") (C++11)(C++11) | atomically obtains the value stored in an atomic object (function template) | | [atomic\_exchangeatomic\_exchange\_explicit](../atomic/atomic_exchange "cpp/atomic/atomic exchange") (C++11)(C++11) | atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template) | | [atomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicitatomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicit](../atomic/atomic_compare_exchange "cpp/atomic/atomic compare exchange") (C++11)(C++11)(C++11)(C++11) | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (function template) | | [atomic\_fetch\_addatomic\_fetch\_add\_explicit](../atomic/atomic_fetch_add "cpp/atomic/atomic fetch add") (C++11)(C++11) | adds a non-atomic value to an atomic object and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](../atomic/atomic_fetch_sub "cpp/atomic/atomic fetch sub") (C++11)(C++11) | subtracts a non-atomic value from an atomic object and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_andatomic\_fetch\_and\_explicit](../atomic/atomic_fetch_and "cpp/atomic/atomic fetch and") (C++11)(C++11) | replaces the atomic object with the result of bitwise AND with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_oratomic\_fetch\_or\_explicit](../atomic/atomic_fetch_or "cpp/atomic/atomic fetch or") (C++11)(C++11) | replaces the atomic object with the result of bitwise OR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](../atomic/atomic_fetch_xor "cpp/atomic/atomic fetch xor") (C++11)(C++11) | replaces the atomic object with the result of bitwise XOR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_waitatomic\_wait\_explicit](../atomic/atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | | [atomic\_notify\_one](../atomic/atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | | [atomic\_notify\_all](../atomic/atomic_notify_all "cpp/atomic/atomic notify all") (C++20) | notifies all threads blocked in atomic\_wait (function template) | | [atomic\_flag\_testatomic\_flag\_test\_explicit](../atomic/atomic_flag_test "cpp/atomic/atomic flag test") (C++20)(C++20) | atomically returns the value of the flag (function) | | [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](../atomic/atomic_flag_test_and_set "cpp/atomic/atomic flag test and set") (C++11)(C++11) | atomically sets the flag to `true` and returns its previous value (function) | | [atomic\_flag\_clearatomic\_flag\_clear\_explicit](../atomic/atomic_flag_clear "cpp/atomic/atomic flag clear") (C++11)(C++11) | atomically sets the value of the flag to `false` (function) | | [atomic\_flag\_waitatomic\_flag\_wait\_explicit](../atomic/atomic_flag_wait "cpp/atomic/atomic flag wait") (C++20)(C++20) | blocks the thread until notified and the flag changes (function) | | [atomic\_flag\_notify\_one](../atomic/atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) | | [atomic\_flag\_notify\_all](../atomic/atomic_flag_notify_all "cpp/atomic/atomic flag notify all") (C++20) | notifies all threads blocked in atomic\_flag\_wait (function) | | [atomic\_init](../atomic/atomic_init "cpp/atomic/atomic init") (C++11)(deprecated in C++20) | non-atomic initialization of a default-constructed atomic object (function template) | | [kill\_dependency](../atomic/kill_dependency "cpp/atomic/kill dependency") (C++11) | removes the specified object from the `[std::memory\_order\_consume](../atomic/memory_order "cpp/atomic/memory order")` dependency tree (function template) | | [atomic\_thread\_fence](../atomic/atomic_thread_fence "cpp/atomic/atomic thread fence") (C++11) | generic memory order-dependent fence synchronization primitive (function) | | [atomic\_signal\_fence](../atomic/atomic_signal_fence "cpp/atomic/atomic signal fence") (C++11) | fence between a thread and a signal handler executed in the same thread (function) | | Macros | | [ATOMIC\_VAR\_INIT](../atomic/atomic_var_init "cpp/atomic/ATOMIC VAR INIT") (C++11)(deprecated in C++20) | constant initialization of an atomic variable of static storage duration (function macro) | | [ATOMIC\_FLAG\_INIT](../atomic/atomic_flag_init "cpp/atomic/ATOMIC FLAG INIT") (C++11) | initializes an `[std::atomic\_flag](../atomic/atomic_flag "cpp/atomic/atomic flag")` to `false` (macro constant) | ### Synopsis ``` namespace std { /* until C++20: typedef enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; */ enum class memory_order : /* unspecified */ { relaxed, consume, acquire, release, acq_rel, seq_cst }; inline constexpr memory_order memory_order_relaxed = memory_order::relaxed; inline constexpr memory_order memory_order_consume = memory_order::consume; inline constexpr memory_order memory_order_acquire = memory_order::acquire; inline constexpr memory_order memory_order_release = memory_order::release; inline constexpr memory_order memory_order_acq_rel = memory_order::acq_rel; inline constexpr memory_order memory_order_seq_cst = memory_order::seq_cst; template<class T> T kill_dependency(T y) noexcept; // lock-free property #define ATOMIC_BOOL_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR8_T_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR16_T_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR32_T_LOCK_FREE /* unspecified */ #define ATOMIC_WCHAR_T_LOCK_FREE /* unspecified */ #define ATOMIC_SHORT_LOCK_FREE /* unspecified */ #define ATOMIC_INT_LOCK_FREE /* unspecified */ #define ATOMIC_LONG_LOCK_FREE /* unspecified */ #define ATOMIC_LLONG_LOCK_FREE /* unspecified */ #define ATOMIC_POINTER_LOCK_FREE /* unspecified */ // class template atomic_ref template<class T> struct atomic_ref; // partial specialization for pointers template<class T> struct atomic_ref<T*>; // class template atomic template<class T> struct atomic; // partial specialization for pointers template<class T> struct atomic<T*>; // non-member functions template<class T> bool atomic_is_lock_free(const volatile atomic<T>*) noexcept; template<class T> bool atomic_is_lock_free(const atomic<T>*) noexcept; template<class T> void atomic_store(volatile atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> void atomic_store(atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> void atomic_store_explicit(volatile atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> void atomic_store_explicit(atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_load(const volatile atomic<T>*) noexcept; template<class T> T atomic_load(const atomic<T>*) noexcept; template<class T> T atomic_load_explicit(const volatile atomic<T>*, memory_order) noexcept; template<class T> T atomic_load_explicit(const atomic<T>*, memory_order) noexcept; template<class T> T atomic_exchange(volatile atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_exchange(atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_exchange_explicit(volatile atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_exchange_explicit(atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> bool atomic_compare_exchange_weak(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type) noexcept; template<class T> bool atomic_compare_exchange_weak(atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type) noexcept; template<class T> bool atomic_compare_exchange_strong(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type) noexcept; template<class T> bool atomic_compare_exchange_strong(atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type) noexcept; template<class T> bool atomic_compare_exchange_weak_explicit(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type, memory_order, memory_order) noexcept; template<class T> bool atomic_compare_exchange_weak_explicit(atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type, memory_order, memory_order) noexcept; template<class T> bool atomic_compare_exchange_strong_explicit(volatile atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type, memory_order, memory_order) noexcept; template<class T> bool atomic_compare_exchange_strong_explicit(atomic<T>*, typename atomic<T>::value_type*, typename atomic<T>::value_type, memory_order, memory_order) noexcept; template<class T> T atomic_fetch_add(volatile atomic<T>*, typename atomic<T>::difference_type) noexcept; template<class T> T atomic_fetch_add(atomic<T>*, typename atomic<T>::difference_type) noexcept; template<class T> T atomic_fetch_add_explicit(volatile atomic<T>*, typename atomic<T>::difference_type, memory_order) noexcept; template<class T> T atomic_fetch_add_explicit(atomic<T>*, typename atomic<T>::difference_type, memory_order) noexcept; template<class T> T atomic_fetch_sub(volatile atomic<T>*, typename atomic<T>::difference_type) noexcept; template<class T> T atomic_fetch_sub(atomic<T>*, typename atomic<T>::difference_type) noexcept; template<class T> T atomic_fetch_sub_explicit(volatile atomic<T>*, typename atomic<T>::difference_type, memory_order) noexcept; template<class T> T atomic_fetch_sub_explicit(atomic<T>*, typename atomic<T>::difference_type, memory_order) noexcept; template<class T> T atomic_fetch_and(volatile atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_fetch_and(atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_fetch_and_explicit(volatile atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_fetch_and_explicit(atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_fetch_or(volatile atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_fetch_or(atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_fetch_or_explicit(volatile atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_fetch_or_explicit(atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_fetch_xor(volatile atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_fetch_xor(atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> T atomic_fetch_xor_explicit(volatile atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> T atomic_fetch_xor_explicit(atomic<T>*, typename atomic<T>::value_type, memory_order) noexcept; template<class T> void atomic_wait(const volatile atomic<T>*, typename atomic<T>::value_type); template<class T> void atomic_wait(const atomic<T>*, typename atomic<T>::value_type); template<class T> void atomic_wait_explicit(const volatile atomic<T>*, typename atomic<T>::value_type, memory_order); template<class T> void atomic_wait_explicit(const atomic<T>*, typename atomic<T>::value_type, memory_order); template<class T> void atomic_notify_one(volatile atomic<T>*); template<class T> void atomic_notify_one(atomic<T>*); template<class T> void atomic_notify_all(volatile atomic<T>*); template<class T> void atomic_notify_all(atomic<T>*); // type aliases using atomic_bool = atomic<bool>; using atomic_char = atomic<char>; using atomic_schar = atomic<signed char>; using atomic_uchar = atomic<unsigned char>; using atomic_short = atomic<short>; using atomic_ushort = atomic<unsigned short>; using atomic_int = atomic<int>; using atomic_uint = atomic<unsigned int>; using atomic_long = atomic<long>; using atomic_ulong = atomic<unsigned long>; using atomic_llong = atomic<long long>; using atomic_ullong = atomic<unsigned long long>; using atomic_char8_t = atomic<char8_t>; using atomic_char16_t = atomic<char16_t>; using atomic_char32_t = atomic<char32_t>; using atomic_wchar_t = atomic<wchar_t>; using atomic_int8_t = atomic<int8_t>; using atomic_uint8_t = atomic<uint8_t>; using atomic_int16_t = atomic<int16_t>; using atomic_uint16_t = atomic<uint16_t>; using atomic_int32_t = atomic<int32_t>; using atomic_uint32_t = atomic<uint32_t>; using atomic_int64_t = atomic<int64_t>; using atomic_uint64_t = atomic<uint64_t>; using atomic_int_least8_t = atomic<int_least8_t>; using atomic_uint_least8_t = atomic<uint_least8_t>; using atomic_int_least16_t = atomic<int_least16_t>; using atomic_uint_least16_t = atomic<uint_least16_t>; using atomic_int_least32_t = atomic<int_least32_t>; using atomic_uint_least32_t = atomic<uint_least32_t>; using atomic_int_least64_t = atomic<int_least64_t>; using atomic_uint_least64_t = atomic<uint_least64_t>; using atomic_int_fast8_t = atomic<int_fast8_t>; using atomic_uint_fast8_t = atomic<uint_fast8_t>; using atomic_int_fast16_t = atomic<int_fast16_t>; using atomic_uint_fast16_t = atomic<uint_fast16_t>; using atomic_int_fast32_t = atomic<int_fast32_t>; using atomic_uint_fast32_t = atomic<uint_fast32_t>; using atomic_int_fast64_t = atomic<int_fast64_t>; using atomic_uint_fast64_t = atomic<uint_fast64_t>; using atomic_intptr_t = atomic<intptr_t>; using atomic_uintptr_t = atomic<uintptr_t>; using atomic_size_t = atomic<size_t>; using atomic_ptrdiff_t = atomic<ptrdiff_t>; using atomic_intmax_t = atomic<intmax_t>; using atomic_uintmax_t = atomic<uintmax_t>; using atomic_signed_lock_free = /* see description */; using atomic_unsigned_lock_free = /* see description */; // flag type and operations struct atomic_flag; bool atomic_flag_test(const volatile atomic_flag*) noexcept; bool atomic_flag_test(const atomic_flag*) noexcept; bool atomic_flag_test_explicit(const volatile atomic_flag*, memory_order) noexcept; bool atomic_flag_test_explicit(const atomic_flag*, memory_order) noexcept; bool atomic_flag_test_and_set(volatile atomic_flag*) noexcept; bool atomic_flag_test_and_set(atomic_flag*) noexcept; bool atomic_flag_test_and_set_explicit(volatile atomic_flag*, memory_order) noexcept; bool atomic_flag_test_and_set_explicit(atomic_flag*, memory_order) noexcept; void atomic_flag_clear(volatile atomic_flag*) noexcept; void atomic_flag_clear(atomic_flag*) noexcept; void atomic_flag_clear_explicit(volatile atomic_flag*, memory_order) noexcept; void atomic_flag_clear_explicit(atomic_flag*, memory_order) noexcept; void atomic_flag_wait(const volatile atomic_flag*, bool) noexcept; void atomic_flag_wait(const atomic_flag*, bool) noexcept; void atomic_flag_wait_explicit(const volatile atomic_flag*, bool, memory_order) noexcept; void atomic_flag_wait_explicit(const atomic_flag*, bool, memory_order) noexcept; void atomic_flag_notify_one(volatile atomic_flag*) noexcept; void atomic_flag_notify_one(atomic_flag*) noexcept; void atomic_flag_notify_all(volatile atomic_flag*) noexcept; void atomic_flag_notify_all(atomic_flag*) noexcept; // fences extern "C" void atomic_thread_fence(memory_order) noexcept; extern "C" void atomic_signal_fence(memory_order) noexcept; } // deprecated namespace std { template<class T> void atomic_init(volatile atomic<T>*, typename atomic<T>::value_type) noexcept; template<class T> void atomic_init(atomic<T>*, typename atomic<T>::value_type) noexcept; #define ATOMIC_VAR_INIT(value) /* see description */ #define ATOMIC_FLAG_INIT /* see description */ } ``` #### Class template `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` ``` namespace std { template<class T> struct atomic { using value_type = T; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const volatile noexcept; bool is_lock_free() const noexcept; // operations on atomic types constexpr atomic() noexcept(is_nothrow_default_constructible_v<T>); constexpr atomic(T) noexcept; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; T load(memory_order = memory_order::seq_cst) const volatile noexcept; T load(memory_order = memory_order::seq_cst) const noexcept; operator T() const volatile noexcept; operator T() const noexcept; void store(T, memory_order = memory_order::seq_cst) volatile noexcept; void store(T, memory_order = memory_order::seq_cst) noexcept; T operator=(T) volatile noexcept; T operator=(T) noexcept; T exchange(T, memory_order = memory_order::seq_cst) volatile noexcept; T exchange(T, memory_order = memory_order::seq_cst) noexcept; bool compare_exchange_weak(T&, T, memory_order, memory_order) volatile noexcept; bool compare_exchange_weak(T&, T, memory_order, memory_order) noexcept; bool compare_exchange_strong(T&, T, memory_order, memory_order) volatile noexcept; bool compare_exchange_strong(T&, T, memory_order, memory_order) noexcept; bool compare_exchange_weak(T&, T, memory_order = memory_order::seq_cst) volatile noexcept; bool compare_exchange_weak(T&, T, memory_order = memory_order::seq_cst) noexcept; bool compare_exchange_strong(T&, T, memory_order = memory_order::seq_cst) volatile noexcept; bool compare_exchange_strong(T&, T, memory_order = memory_order::seq_cst) noexcept; void wait(T, memory_order = memory_order::seq_cst) const volatile noexcept; void wait(T, memory_order = memory_order::seq_cst) const noexcept; void notify_one() volatile noexcept; void notify_one() noexcept; void notify_all() volatile noexcept; void notify_all() noexcept; }; } ``` #### Specializations of `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` for integral types ``` namespace std { template<> struct atomic</* integral */> { using value_type = /* integral */; using difference_type = value_type; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const volatile noexcept; bool is_lock_free() const noexcept; constexpr atomic() noexcept; constexpr atomic(/* integral */) noexcept; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; void store(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; void store(/* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ operator=(/* integral */) volatile noexcept; /* integral */ operator=(/* integral */) noexcept; /* integral */ load(memory_order = memory_order::seq_cst) const volatile noexcept; /* integral */ load(memory_order = memory_order::seq_cst) const noexcept; operator /* integral */() const volatile noexcept; operator /* integral */() const noexcept; /* integral */ exchange(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; /* integral */ exchange(/* integral */, memory_order = memory_order::seq_cst) noexcept; bool compare_exchange_weak(/* integral */&, /* integral */, memory_order, memory_order) volatile noexcept; bool compare_exchange_weak(/* integral */&, /* integral */, memory_order, memory_order) noexcept; bool compare_exchange_strong(/* integral */&, /* integral */, memory_order, memory_order) volatile noexcept; bool compare_exchange_strong(/* integral */&, /* integral */, memory_order, memory_order) noexcept; bool compare_exchange_weak(/* integral */&, /* integral */, memory_order = memory_order::seq_cst) volatile noexcept; bool compare_exchange_weak(/* integral */&, /* integral */, memory_order = memory_order::seq_cst) noexcept; bool compare_exchange_strong(/* integral */&, /* integral */, memory_order = memory_order::seq_cst) volatile noexcept; bool compare_exchange_strong(/* integral */&, /* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ fetch_add(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; /* integral */ fetch_add(/* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ fetch_sub(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; /* integral */ fetch_sub(/* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ fetch_and(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; /* integral */ fetch_and(/* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ fetch_or(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; /* integral */ fetch_or(/* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ fetch_xor(/* integral */, memory_order = memory_order::seq_cst) volatile noexcept; /* integral */ fetch_xor(/* integral */, memory_order = memory_order::seq_cst) noexcept; /* integral */ operator++(int) volatile noexcept; /* integral */ operator++(int) noexcept; /* integral */ operator--(int) volatile noexcept; /* integral */ operator--(int) noexcept; /* integral */ operator++() volatile noexcept; /* integral */ operator++() noexcept; /* integral */ operator--() volatile noexcept; /* integral */ operator--() noexcept; /* integral */ operator+=(/* integral */) volatile noexcept; /* integral */ operator+=(/* integral */) noexcept; /* integral */ operator-=(/* integral */) volatile noexcept; /* integral */ operator-=(/* integral */) noexcept; /* integral */ operator&=(/* integral */) volatile noexcept; /* integral */ operator&=(/* integral */) noexcept; /* integral */ operator|=(/* integral */) volatile noexcept; /* integral */ operator|=(/* integral */) noexcept; /* integral */ operator^=(/* integral */) volatile noexcept; /* integral */ operator^=(/* integral */) noexcept; void wait(/* integral */, memory_order = memory_order::seq_cst) const volatile noexcept; void wait(/* integral */, memory_order = memory_order::seq_cst) const noexcept; void notify_one() volatile noexcept; void notify_one() noexcept; void notify_all() volatile noexcept; void notify_all() noexcept; }; } ``` #### Specializations of `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` for floating-point types ``` namespace std { template<> struct atomic</* floating-point */> { using value_type = /* floating-point */; using difference_type = value_type; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const volatile noexcept; bool is_lock_free() const noexcept; constexpr atomic() noexcept; constexpr atomic(/* floating-point */) noexcept; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; void store(/* floating-point */, memory_order = memory_order_seq_cst) volatile noexcept; void store(/* floating-point */, memory_order = memory_order_seq_cst) noexcept; /* floating-point */ operator=(/* floating-point */) volatile noexcept; /* floating-point */ operator=(/* floating-point */) noexcept; /* floating-point */ load(memory_order = memory_order_seq_cst) volatile noexcept; /* floating-point */ load(memory_order = memory_order_seq_cst) noexcept; operator /* floating-point */() volatile noexcept; operator /* floating-point */() noexcept; /* floating-point */ exchange(/* floating-point */, memory_order = memory_order_seq_cst) volatile noexcept; /* floating-point */ exchange(/* floating-point */, memory_order = memory_order_seq_cst) noexcept; bool compare_exchange_weak(/* floating-point */&, /* floating-point */, memory_order, memory_order) volatile noexcept; bool compare_exchange_weak(/* floating-point */&, /* floating-point */, memory_order, memory_order) noexcept; bool compare_exchange_strong(/* floating-point */&, /* floating-point */, memory_order, memory_order) volatile noexcept; bool compare_exchange_strong(/* floating-point */&, /* floating-point */, memory_order, memory_order) noexcept; bool compare_exchange_weak(/* floating-point */&, /* floating-point */, memory_order = memory_order_seq_cst) volatile noexcept; bool compare_exchange_weak(/* floating-point */&, /* floating-point */, memory_order = memory_order_seq_cst) noexcept; bool compare_exchange_strong(/* floating-point */&, /* floating-point */, memory_order = memory_order_seq_cst) volatile noexcept; bool compare_exchange_strong(/* floating-point */&, /* floating-point */, memory_order = memory_order_seq_cst) noexcept; /* floating-point */ fetch_add(/* floating-point */, memory_order = memory_order_seq_cst) volatile noexcept; /* floating-point */ fetch_add(/* floating-point */, memory_order = memory_order_seq_cst) noexcept; /* floating-point */ fetch_sub(/* floating-point */, memory_order = memory_order_seq_cst) volatile noexcept; /* floating-point */ fetch_sub(/* floating-point */, memory_order = memory_order_seq_cst) noexcept; /* floating-point */ operator+=(/* floating-point */) volatile noexcept; /* floating-point */ operator+=(/* floating-point */) noexcept; /* floating-point */ operator-=(/* floating-point */) volatile noexcept; /* floating-point */ operator-=(/* floating-point */) noexcept; void wait(/* floating-point */, memory_order = memory_order::seq_cst) const volatile noexcept; void wait(/* floating-point */, memory_order = memory_order::seq_cst) const noexcept; void notify_one() volatile noexcept; void notify_one() noexcept; void notify_all() volatile noexcept; void notify_all() noexcept; }; } ``` #### Specializations of `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` for pointer types ``` namespace std { template<class T> struct atomic<T*> { using value_type = T*; using difference_type = ptrdiff_t; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const volatile noexcept; bool is_lock_free() const noexcept; constexpr atomic() noexcept; constexpr atomic(T*) noexcept; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; void store(T*, memory_order = memory_order::seq_cst) volatile noexcept; void store(T*, memory_order = memory_order::seq_cst) noexcept; T* operator=(T*) volatile noexcept; T* operator=(T*) noexcept; T* load(memory_order = memory_order::seq_cst) const volatile noexcept; T* load(memory_order = memory_order::seq_cst) const noexcept; operator T*() const volatile noexcept; operator T*() const noexcept; T* exchange(T*, memory_order = memory_order::seq_cst) volatile noexcept; T* exchange(T*, memory_order = memory_order::seq_cst) noexcept; bool compare_exchange_weak(T*&, T*, memory_order, memory_order) volatile noexcept; bool compare_exchange_weak(T*&, T*, memory_order, memory_order) noexcept; bool compare_exchange_strong(T*&, T*, memory_order, memory_order) volatile noexcept; bool compare_exchange_strong(T*&, T*, memory_order, memory_order) noexcept; bool compare_exchange_weak(T*&, T*, memory_order = memory_order::seq_cst) volatile noexcept; bool compare_exchange_weak(T*&, T*, memory_order = memory_order::seq_cst) noexcept; bool compare_exchange_strong(T*&, T*, memory_order = memory_order::seq_cst) volatile noexcept; bool compare_exchange_strong(T*&, T*, memory_order = memory_order::seq_cst) noexcept; T* fetch_add(ptrdiff_t, memory_order = memory_order::seq_cst) volatile noexcept; T* fetch_add(ptrdiff_t, memory_order = memory_order::seq_cst) noexcept; T* fetch_sub(ptrdiff_t, memory_order = memory_order::seq_cst) volatile noexcept; T* fetch_sub(ptrdiff_t, memory_order = memory_order::seq_cst) noexcept; T* operator++(int) volatile noexcept; T* operator++(int) noexcept; T* operator--(int) volatile noexcept; T* operator--(int) noexcept; T* operator++() volatile noexcept; T* operator++() noexcept; T* operator--() volatile noexcept; T* operator--() noexcept; T* operator+=(ptrdiff_t) volatile noexcept; T* operator+=(ptrdiff_t) noexcept; T* operator-=(ptrdiff_t) volatile noexcept; T* operator-=(ptrdiff_t) noexcept; void wait(T*, memory_order = memory_order::seq_cst) const volatile noexcept; void wait(T*, memory_order = memory_order::seq_cst) const noexcept; void notify_one() volatile noexcept; void notify_one() noexcept; void notify_all() volatile noexcept; void notify_all() noexcept; }; } ``` #### Class template `std::atomic_ref` ``` namespace std { template<class T> struct atomic_ref { private: T* ptr; // exposition only public: using value_type = T; static constexpr size_t required_alignment = /* implementation-defined */; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const noexcept; explicit atomic_ref(T&); atomic_ref(const atomic_ref&) noexcept; atomic_ref& operator=(const atomic_ref&) = delete; void store(T, memory_order = memory_order_seq_cst) const noexcept; T operator=(T) const noexcept; T load(memory_order = memory_order_seq_cst) const noexcept; operator T() const noexcept; T exchange(T, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_weak(T&, T, memory_order, memory_order) const noexcept; bool compare_exchange_strong(T&, T, memory_order, memory_order) const noexcept; bool compare_exchange_weak(T&, T, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_strong(T&, T, memory_order = memory_order_seq_cst) const noexcept; void wait(T, memory_order = memory_order::seq_cst) const noexcept; void notify_one() const noexcept; void notify_all() const noexcept; }; } ``` #### Specializations of `std::atomic_ref` for integral types ``` namespace std { template<> struct atomic_ref</* integral */> { private: /* integral */* ptr; // exposition only public: using value_type = /* integral */; using difference_type = value_type; static constexpr size_t required_alignment = /* implementation-defined */; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const noexcept; explicit atomic_ref(/* integral */&); atomic_ref(const atomic_ref&) noexcept; atomic_ref& operator=(const atomic_ref&) = delete; void store(/* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ operator=(/* integral */) const noexcept; /* integral */ load(memory_order = memory_order_seq_cst) const noexcept; operator /* integral */() const noexcept; /* integral */ exchange(/* integral */, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_weak(/* integral */&, /* integral */, memory_order, memory_order) const noexcept; bool compare_exchange_strong(/* integral */&, /* integral */, memory_order, memory_order) const noexcept; bool compare_exchange_weak(/* integral */&, /* integral */, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_strong(/* integral */&, /* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ fetch_add(/* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ fetch_sub(/* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ fetch_and(/* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ fetch_or(/* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ fetch_xor(/* integral */, memory_order = memory_order_seq_cst) const noexcept; /* integral */ operator++(int) const noexcept; /* integral */ operator--(int) const noexcept; /* integral */ operator++() const noexcept; /* integral */ operator--() const noexcept; /* integral */ operator+=(/* integral */) const noexcept; /* integral */ operator-=(/* integral */) const noexcept; /* integral */ operator&=(/* integral */) const noexcept; /* integral */ operator ``` #### Specializations of `std::atomic_ref` for floating-point types ``` namespace std { template<> struct atomic_ref</* floating-point */> { private: /* floating-point */* ptr; // exposition only public: using value_type = /* floating-point */; using difference_type = value_type; static constexpr size_t required_alignment = /* implementation-defined */; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const noexcept; explicit atomic_ref(/* floating-point */&); atomic_ref(const atomic_ref&) noexcept; atomic_ref& operator=(const atomic_ref&) = delete; void store(/* floating-point */, memory_order = memory_order_seq_cst) const noexcept; /* floating-point */ operator=(/* floating-point */) const noexcept; /* floating-point */ load(memory_order = memory_order_seq_cst) const noexcept; operator /* floating-point */() const noexcept; /* floating-point */ exchange(/* floating-point */, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_weak(/* floating-point */&, /* floating-point */, memory_order, memory_order) const noexcept; bool compare_exchange_strong(/* floating-point */&, /* floating-point */, memory_order, memory_order) const noexcept; bool compare_exchange_weak(/* floating-point */&, /* floating-point */, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_strong(/* floating-point */&, /* floating-point */, memory_order = memory_order_seq_cst) const noexcept; /* floating-point */ fetch_add(/* floating-point */, memory_order = memory_order_seq_cst) const noexcept; /* floating-point */ fetch_sub(/* floating-point */, memory_order = memory_order_seq_cst) const noexcept; /* floating-point */ operator+=(/* floating-point */) const noexcept; /* floating-point */ operator-=(/* floating-point */) const noexcept; void wait(/* floating-point */, memory_order = memory_order::seq_cst) const noexcept; void notify_one() const noexcept; void notify_all() const noexcept; }; } ``` #### Specializations of `std::atomic_ref` for pointer types ``` namespace std { template<class T> struct atomic_ref<T*> { private: T** ptr; // exposition only public: using value_type = T*; using difference_type = ptrdiff_t; static constexpr size_t required_alignment = /* implementation-defined */; static constexpr bool is_always_lock_free = /* implementation-defined */; bool is_lock_free() const noexcept; explicit atomic_ref(T*&); atomic_ref(const atomic_ref&) noexcept; atomic_ref& operator=(const atomic_ref&) = delete; void store(T*, memory_order = memory_order_seq_cst) const noexcept; T* operator=(T*) const noexcept; T* load(memory_order = memory_order_seq_cst) const noexcept; operator T*() const noexcept; T* exchange(T*, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_weak(T*&, T*, memory_order, memory_order) const noexcept; bool compare_exchange_strong(T*&, T*, memory_order, memory_order) const noexcept; bool compare_exchange_weak(T*&, T*, memory_order = memory_order_seq_cst) const noexcept; bool compare_exchange_strong(T*&, T*, memory_order = memory_order_seq_cst) const noexcept; T* fetch_add(difference_type, memory_order = memory_order_seq_cst) const noexcept; T* fetch_sub(difference_type, memory_order = memory_order_seq_cst) const noexcept; T* operator++(int) const noexcept; T* operator--(int) const noexcept; T* operator++() const noexcept; T* operator--() const noexcept; T* operator+=(difference_type) const noexcept; T* operator-=(difference_type) const noexcept; void wait(T*, memory_order = memory_order::seq_cst) const noexcept; void notify_one() const noexcept; void notify_all() const noexcept; }; } ``` #### Class `[std::atomic\_flag](../atomic/atomic_flag "cpp/atomic/atomic flag")` ``` namespace std { struct atomic_flag { constexpr atomic_flag() noexcept; atomic_flag(const atomic_flag&) = delete; atomic_flag& operator=(const atomic_flag&) = delete; atomic_flag& operator=(const atomic_flag&) volatile = delete; bool test(memory_order = memory_order::seq_cst) const volatile noexcept; bool test(memory_order = memory_order::seq_cst) const noexcept; bool test_and_set(memory_order = memory_order::seq_cst) volatile noexcept; bool test_and_set(memory_order = memory_order::seq_cst) noexcept; void clear(memory_order = memory_order::seq_cst) volatile noexcept; void clear(memory_order = memory_order::seq_cst) noexcept; void wait(bool, memory_order = memory_order::seq_cst) const volatile noexcept; void wait(bool, memory_order = memory_order::seq_cst) const noexcept; void notify_one() volatile noexcept; void notify_one() noexcept; void notify_all() volatile noexcept; void notify_all() noexcept; }; } ```
programming_docs
cpp Standard library header <deque> Standard library header <deque> =============================== This header is part of the [containers](../container "cpp/container") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | [<initializer\_list>](initializer_list "cpp/header/initializer list") (C++11) | `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` class template | | Classes | | [deque](../container/deque "cpp/container/deque") | double-ended queue (class template) | | Functions | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/deque/operator_cmp "cpp/container/deque/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the deque (function template) | | [std::swap(std::deque)](../container/deque/swap2 "cpp/container/deque/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::deque)erase\_if(std::deque)](../container/deque/erase2 "cpp/container/deque/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | | Range access | | [begincbegin](../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | | [endcend](../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | | [rbegincrbegin](../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | | [rendcrend](../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | | [sizessize](../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [empty](../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [data](../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | ### Synopsis ``` #include <compare> #include <initializer_list> namespace std { // class template deque template<class T, class Allocator = allocator<T>> class deque; template<class T, class Allocator> bool operator==(const deque<T, Allocator>& x, const deque<T, Allocator>& y); template<class T, class Allocator> /*synth-three-way-result*/<T> operator<=>(const deque<T, Allocator>& x, const deque<T, Allocator>& y); template<class T, class Allocator> void swap(deque<T, Allocator>& x, deque<T, Allocator>& y) noexcept(noexcept(x.swap(y))); template<class T, class Allocator, class U> typename deque<T, Allocator>::size_type erase(deque<T, Allocator>& c, const U& value); template<class T, class Allocator, class Predicate> typename deque<T, Allocator>::size_type erase_if(deque<T, Allocator>& c, Predicate pred); namespace pmr { template<class T> using deque = std::deque<T, polymorphic_allocator<T>>; } } ``` ### Class template `[std::deque](../container/deque "cpp/container/deque")` ``` namespace std { template<class T, class Allocator = allocator<T>> class deque { public: // types using value_type = T; using allocator_type = Allocator; using pointer = typename allocator_traits<Allocator>::pointer; using const_pointer = typename allocator_traits<Allocator>::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = /* implementation-defined */; using difference_type = /* implementation-defined */; using iterator = /* implementation-defined */; using const_iterator = /* implementation-defined */; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // construct/copy/destroy deque() : deque(Allocator()) { } explicit deque(const Allocator&); explicit deque(size_type n, const Allocator& = Allocator()); deque(size_type n, const T& value, const Allocator& = Allocator()); template<class InputIt> deque(InputIt first, InputIt last, const Allocator& = Allocator()); deque(const deque& x); deque(deque&&); deque(const deque&, const Allocator&); deque(deque&&, const Allocator&); deque(initializer_list<T>, const Allocator& = Allocator()); ~deque(); deque& operator=(const deque& x); deque& operator=(deque&& x) noexcept(allocator_traits<Allocator>::is_always_equal::value); deque& operator=(initializer_list<T>); template<class InputIt> void assign(InputIt first, InputIt last); void assign(size_type n, const T& t); void assign(initializer_list<T>); allocator_type get_allocator() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; // capacity [[nodiscard]] bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; void resize(size_type sz); void resize(size_type sz, const T& c); void shrink_to_fit(); // element access reference operator[](size_type n); const_reference operator[](size_type n) const; reference at(size_type n); const_reference at(size_type n) const; reference front(); const_reference front() const; reference back(); const_reference back() const; // modifiers template<class... Args> reference emplace_front(Args&&... args); template<class... Args> reference emplace_back(Args&&... args); template<class... Args> iterator emplace(const_iterator position, Args&&... args); void push_front(const T& x); void push_front(T&& x); void push_back(const T& x); void push_back(T&& x); iterator insert(const_iterator position, const T& x); iterator insert(const_iterator position, T&& x); iterator insert(const_iterator position, size_type n, const T& x); template<class InputIt> iterator insert(const_iterator position, InputIt first, InputIt last); iterator insert(const_iterator position, initializer_list<T>); void pop_front(); void pop_back(); iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last); void swap(deque&) noexcept(allocator_traits<Allocator>::is_always_equal::value); void clear() noexcept; }; template<class InputIt, class Allocator = allocator</*iter-value-type*/<InputIt>>> deque(InputIt, InputIt, Allocator = Allocator()) -> deque</*iter-value-type*/<InputIt>, Allocator>; // swap template<class T, class Allocator> void swap(deque<T, Allocator>& x, deque<T, Allocator>& y) noexcept(noexcept(x.swap(y))); } ``` cpp Standard library header <system_error> (C++11) Standard library header <system\_error> (C++11) =============================================== This header is part of the [error handling](../error "cpp/error") library. | | | --- | | Includes | | [<compare>](compare "cpp/header/compare") (C++20) | [Three-way comparison operator](../language/operator_comparison#Three-way_comparison "cpp/language/operator comparison") support | | Classes | | [error\_category](../error/error_category "cpp/error/error category") (C++11) | base class for error categories (class) | | [error\_condition](../error/error_condition "cpp/error/error condition") (C++11) | holds a portable error code (class) | | [errc](../error/errc "cpp/error/errc") (C++11) | the `[std::error\_condition](../error/error_condition "cpp/error/error condition")` enumeration listing all standard [`<cerrno>`](cerrno "cpp/header/cerrno") macro constants (class) | | [error\_code](../error/error_code "cpp/error/error code") (C++11) | holds a platform-dependent error code (class) | | [system\_error](../error/system_error "cpp/error/system error") (C++11) | exception class used to report conditions that have an error\_code (class) | | [is\_error\_code\_enum](../error/error_code/is_error_code_enum "cpp/error/error code/is error code enum") (C++11) | identifies a class as an error\_code enumeration (class template) | | [is\_error\_condition\_enum](../error/error_condition/is_error_condition_enum "cpp/error/error condition/is error condition enum") (C++11) | identifies an enumeration as an `[std::error\_condition](../error/error_condition "cpp/error/error condition")` (class template) | | [std::hash<std::error\_code>](../error/error_code/hash "cpp/error/error code/hash") (C++11) | hash support for `[std::error\_code](../error/error_code "cpp/error/error code")` (class template specialization) | | Forward declarations | | Defined in header `[<functional>](functional "cpp/header/functional")` | | [hash](../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | Functions | | [generic\_category](../error/generic_category "cpp/error/generic category") (C++11) | identifies the generic error category (function) | | [system\_category](../error/system_category "cpp/error/system category") (C++11) | identifies the operating system error category (function) | | [operator==operator!=operator<operator<=>](../error/error_code/operator_cmp "cpp/error/error code/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares two `error_code`s (function) | | [operator<<](../error/error_code/operator_ltlt "cpp/error/error code/operator ltlt") | outputs the value and the category name to an output stream (function) | | [make\_error\_code(std::errc)](../error/errc/make_error_code "cpp/error/errc/make error code") (C++11) | constructs an `[std::errc](../error/errc "cpp/error/errc")` error code (function) | | [operator==operator!=operator<operator<=>](../error/error_condition/operator_cmp "cpp/error/error condition/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares `error_condition`s and `error_code`s (function) | | [make\_error\_condition(std::errc)](../error/errc/make_error_condition "cpp/error/errc/make error condition") (C++11) | constructs an `[std::errc](../error/errc "cpp/error/errc")` error condition (function) | ### Synopsis ``` #include <compare> namespace std { class error_category; const error_category& generic_category() noexcept; const error_category& system_category() noexcept; class error_code; class error_condition; class system_error; template<class T> struct is_error_code_enum : public false_type {}; template<class T> struct is_error_condition_enum : public false_type {}; enum class errc { address_family_not_supported, // EAFNOSUPPORT address_in_use, // EADDRINUSE address_not_available, // EADDRNOTAVAIL already_connected, // EISCONN argument_list_too_long, // E2BIG argument_out_of_domain, // EDOM bad_address, // EFAULT bad_file_descriptor, // EBADF bad_message, // EBADMSG broken_pipe, // EPIPE connection_aborted, // ECONNABORTED connection_already_in_progress, // EALREADY connection_refused, // ECONNREFUSED connection_reset, // ECONNRESET cross_device_link, // EXDEV destination_address_required, // EDESTADDRREQ device_or_resource_busy, // EBUSY directory_not_empty, // ENOTEMPTY executable_format_error, // ENOEXEC file_exists, // EEXIST file_too_large, // EFBIG filename_too_long, // ENAMETOOLONG function_not_supported, // ENOSYS host_unreachable, // EHOSTUNREACH identifier_removed, // EIDRM illegal_byte_sequence, // EILSEQ inappropriate_io_control_operation, // ENOTTY interrupted, // EINTR invalid_argument, // EINVAL invalid_seek, // ESPIPE io_error, // EIO is_a_directory, // EISDIR message_size, // EMSGSIZE network_down, // ENETDOWN network_reset, // ENETRESET network_unreachable, // ENETUNREACH no_buffer_space, // ENOBUFS no_child_process, // ECHILD no_link, // ENOLINK no_lock_available, // ENOLCK no_message_available, // ENODATA no_message, // ENOMSG no_protocol_option, // ENOPROTOOPT no_space_on_device, // ENOSPC no_stream_resources, // ENOSR no_such_device_or_address, // ENXIO no_such_device, // ENODEV no_such_file_or_directory, // ENOENT no_such_process, // ESRCH not_a_directory, // ENOTDIR not_a_socket, // ENOTSOCK not_a_stream, // ENOSTR not_connected, // ENOTCONN not_enough_memory, // ENOMEM not_supported, // ENOTSUP operation_canceled, // ECANCELED operation_in_progress, // EINPROGRESS operation_not_permitted, // EPERM operation_not_supported, // EOPNOTSUPP operation_would_block, // EWOULDBLOCK owner_dead, // EOWNERDEAD permission_denied, // EACCES protocol_error, // EPROTO protocol_not_supported, // EPROTONOSUPPORT read_only_file_system, // EROFS resource_deadlock_would_occur, // EDEADLK resource_unavailable_try_again, // EAGAIN result_out_of_range, // ERANGE state_not_recoverable, // ENOTRECOVERABLE stream_timeout, // ETIME text_file_busy, // ETXTBSY timed_out, // ETIMEDOUT too_many_files_open_in_system, // ENFILE too_many_files_open, // EMFILE too_many_links, // EMLINK too_many_symbolic_link_levels, // ELOOP value_too_large, // EOVERFLOW wrong_protocol_type, // EPROTOTYPE }; template<> struct is_error_condition_enum<errc> : true_type {}; // non-member functions error_code make_error_code(errc e) noexcept; template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const error_code& ec); // non-member functions error_condition make_error_condition(errc e) noexcept; // comparison functions bool operator==(const error_code& lhs, const error_code& rhs) noexcept; bool operator==(const error_code& lhs, const error_condition& rhs) noexcept; bool operator==(const error_condition& lhs, const error_condition& rhs) noexcept; strong_ordering operator<=>(const error_code& lhs, const error_code& rhs) noexcept; strong_ordering operator<=>(const error_condition& lhs, const error_condition& rhs) noexcept; // hash support template<class T> struct hash; template<> struct hash<error_code>; template<> struct hash<error_condition>; // system error support template<class T> inline constexpr bool is_error_code_enum_v = is_error_code_enum<T>::value; template<class T> inline constexpr bool is_error_condition_enum_v = is_error_condition_enum<T>::value; } ``` #### Class `[std::error\_category](../error/error_category "cpp/error/error category")` ``` namespace std { class error_category { public: constexpr error_category() noexcept; virtual ~error_category(); error_category(const error_category&) = delete; error_category& operator=(const error_category&) = delete; virtual const char* name() const noexcept = 0; virtual error_condition default_error_condition(int ev) const noexcept; virtual bool equivalent(int code, const error_condition& condition) const noexcept; virtual bool equivalent(const error_code& code, int condition) const noexcept; virtual string message(int ev) const = 0; bool operator==(const error_category& rhs) const noexcept; strong_ordering operator<=>(const error_category& rhs) const noexcept; }; const error_category& generic_category() noexcept; const error_category& system_category() noexcept; } ``` #### Class `[std::error\_code](../error/error_code "cpp/error/error code")` ``` namespace std { class error_code { public: // constructors error_code() noexcept; error_code(int val, const error_category& cat) noexcept; template<class ErrorCodeEnum> error_code(ErrorCodeEnum e) noexcept; // modifiers void assign(int val, const error_category& cat) noexcept; template<class ErrorCodeEnum> error_code& operator=(ErrorCodeEnum e) noexcept; void clear() noexcept; // observers int value() const noexcept; const error_category& category() const noexcept; error_condition default_error_condition() const noexcept; string message() const; explicit operator bool() const noexcept; private: int val_; // exposition only const error_category* cat_; // exposition only }; // non-member functions error_code make_error_code(errc e) noexcept; template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const error_code& ec); } ``` #### Class `[std::error\_condition](../error/error_condition "cpp/error/error condition")` ``` namespace std { class error_condition { public: // constructors error_condition() noexcept; error_condition(int val, const error_category& cat) noexcept; template<class ErrorConditionEnum> error_condition(ErrorConditionEnum e) noexcept; // modifiers void assign(int val, const error_category& cat) noexcept; template<class ErrorConditionEnum> error_condition& operator=(ErrorConditionEnum e) noexcept; void clear() noexcept; // observers int value() const noexcept; const error_category& category() const noexcept; string message() const; explicit operator bool() const noexcept; private: int val_; // exposition only const error_category* cat_; // exposition only }; } ``` #### Class `[std::system\_error](../error/system_error "cpp/error/system error")` ``` namespace std { class system_error : public runtime_error { public: system_error(error_code ec, const string& what_arg); system_error(error_code ec, const char* what_arg); system_error(error_code ec); system_error(int ev, const error_category& ecat, const string& what_arg); system_error(int ev, const error_category& ecat, const char* what_arg); system_error(int ev, const error_category& ecat); const error_code& code() const noexcept; const char* what() const noexcept override; }; } ```
programming_docs