В этом разделе описаны компоненты для управления последовательностями любых не-массивов POD type. Такие типы называются char-like types, а объекты символьных типов называются char-like objects или просто characters.
Следующие подпункты описывают класс характеристик символа, класс строки и утилиты последовательностей с нулевым символом в конце, как показано в таблице 53.
Подпункт | Заголовок (ы) | |
[char.traits] | Черты характера | <string> |
[string.classes] | Строковые классы | <string> |
[string.view] | Классы строковых представлений | <string_view> |
<cctype> | ||
<cwctype> | ||
[c.strings] | Утилиты для последовательностей с нулевым завершением | <cstring> |
<cwchar> | ||
<cstdlib> | ||
<cuchar> |
В этом подразделе определяются требования по классам , представляющих
character traitsи определяет шаблон класса
char_traits<charT>, наряду с четырьмя специализациями,
char_traits<char>,
char_traits<char16_t>,
char_traits<char32_t>, и
char_traits<wchar_t>, которые удовлетворяют этим требованиям.
Большинство классов , указанных в пунктах [string.classes] и [input.output] нужен набор связанных типов и функций , чтобы завершить определение их семантики. Эти типы и функции предоставляются как набор членов typedef-names и функций в параметре шаблона, traits используемом каждым таким шаблоном. В этом подпункте определяется семантика этих членов.
Чтобы специализировать эти шаблоны для создания строки или класса iostream для обработки определенного типа контейнера символов CharT, этот и связанный с ним класс характеристик символов Traits передаются в виде пары параметров в строку или шаблон iostream как параметры charT и traits. Traits::char_type должно быть таким же, как CharT.
Этот подраздел определяет шаблон класса, char_traits<charT>и четыре явных специализаций этого, char_traits<char>, char_traits<char16_t>, char_traits<char32_t>, и char_traits<wchar_t>, все из которых появляются в заголовке <string> и удовлетворяют требования ниже.
В таблице 54, X обозначает класс черты , определяющий типы и функции для символьного типа контейнера CharT; c и d обозначают значения типа CharT; p и q обозначают значения типа const CharT*; s обозначает значение типа CharT*; n, i и j обозначают значения типа size_t; e и f обозначают значения типа X::int_type; pos обозначает значение типа X::pos_type; state обозначает значение типа X::state_type; и r обозначает lvalue типа CharT. Операции с Чертами не должны вызывать исключений.
Выражение | Тип возврата | Утверждение / примечание | Сложность |
до / после состояния | |||
X::char_type | charT | (описано в [char.traits.typedefs]) | время компиляции |
X::int_type | (описано в [char.traits.typedefs]) | время компиляции | |
X::off_type | (описано в [char.traits.typedefs]) | время компиляции | |
X::pos_type | (описано в [char.traits.typedefs]) | время компиляции | |
X::state_type | (описано в [char.traits.typedefs]) | время компиляции | |
X::eq(c,d) | bool | Returns: следует ли c рассматривать как равное d. | постоянный |
X::lt(c,d) | bool | Returns: следует ли c рассматривать как меньшее, чем d. | постоянный |
X::compare(p,q,n) | int | Returns: 0 если для каждого i в [0,n), X::eq(p[i],q[i]) есть true; иначе, отрицательное значение , если для некоторых j ин [0,n), X::lt(p[j],q[j]) это true и для каждого i дюйма [0,j) X::eq(p[i],q[i]) является true; иначе положительное значение. | линейный |
X::length(p) | size_t | Returns: самый маленький i такой что X::eq(p[i],charT()) есть true. | линейный |
X::find(p,n,c) | const X::char_type* | Returns: наименьшее q в [p,p+n) таком, то X::eq(*q,c) есть true, в противном случае ноль. | линейный |
X::move(s,p,n) | X::char_type* |
для каждого i в [0,n), выполняет X::assign(s[i],p[i]). Копирует правильно даже там, где диапазоны [p,p+n) и [s,s+n) перекрываются. Returns: s. | линейный |
X::copy(s,p,n) | X::char_type* |
Requires: p не в [s,s+n). Returns: s. для каждого i в [0,n), выполняет X::assign(s[i],p[i]). | линейный |
X::assign(r,d) | (не используется) | назначает r=d. | постоянный |
X::assign(s,n,c) | X::char_type* |
для каждого i в [0,n), выполняет
X::assign(s[i],c). Returns: s. | линейный |
X::not_eof(e) | int_type | Returns: e если X::eq_int_type(e,X::eof()) есть false, в противном случае такое значение f , которое X::eq_int_type(f,X::eof()) есть false. | постоянный |
X::to_char_type(e) | X::char_type | Returns: если для некоторых c, X::eq_int_type(e,X::to_int_type(c)) это true, c; иначе какое-то неопределенное значение. | постоянный |
X::to_int_type(c) | X::int_type | Returns: некоторая ценность e, ограниченная определениями to_char_type и eq_int_type. | постоянный |
X::eq_int_type(e,f) | bool | Returns: для всех c и d, X::eq(c,d) равно X::eq_int_type(X::to_int_type(c), X::to_int_type(d)); в противном случае выдает true if e и f обе копии X::eof(); в противном случае уступает, false если одно из e и f является копией, X::eof() а другое - нет; в противном случае значение не указано. | постоянный |
X::eof() | X::int_type | Returns: такое значение e , которое X::eq_int_type(e,X::to_int_type(c)) есть false для всех значений c. | постоянный |
using char_type = CHAR_T;
Тип char_type используется для ссылки на тип символьного контейнера в реализации библиотечных классов, определенных в [string.classes] разделе и [input.output].
using int_type = INT_T;
Requires: Для определенного типа характера контейнера char_type, связанный тип контейнера INT_T должен быть типа или класса , который может представлять все допустимые символы , преобразованных из соответствующих char_type значений, а также значение конца-файла eof(). Типint_type представляет собой тип символьного контейнера, который может содержать конец файла, который будет использоваться в качестве возвращаемого типа функций-членов класса iostream.224
using off_type = implementation-defined;
using pos_type = implementation-defined;
Requires: Требования к off_type и pos_type описаны в [iostreams.limits.pos] и [iostream.forward].
using state_type = STATE_T;
Requires: state_type должны отвечать требованиям CopyAssignable, CopyConstructibleи DefaultConstructible типов.
Если их eof() можно char_type удержать, то некоторые операции iostreams могут дать удивительные результаты.
namespace std { template<> struct char_traits<char>; template<> struct char_traits<char16_t>; template<> struct char_traits<char32_t>; template<> struct char_traits<wchar_t>; }
Заголовок <string> определяет четыре специализации шаблона класса char_traits: char_traits<char>, char_traits<char16_t>, char_traits<char32_t>, и char_traits<wchar_t>.
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; 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 char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static 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; }; }
Определенные типы для int_type, pos_type, off_typeи state_type должно быть int, streampos, streamoffи mbstate_t соответственно.
Типstreampos должен быть типом , определяемым реализацией, который удовлетворяет требованиям pos_type в [iostreams.limits.pos] и [iostream.forward].
Типstreamoff должен быть типом , определяемым реализацией, который удовлетворяет требованиям off_type в [iostreams.limits.pos] и [iostream.forward].
Тип mbstate_t определяется <cwchar> и может представлять любое из состояний преобразования, которое может происходить в определяемом реализацией наборе поддерживаемых правил кодирования многобайтовых символов.
Член с двумя аргументами assign должен быть определен идентично встроенному оператору =. Члены с двумя аргументами eq и lt должны быть определены идентично встроенным операторам == и < типу unsigned char.
namespace std { 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; 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 char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static 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; }; }
Типu16streampos должен быть типом , определяемым реализацией, который удовлетворяет требованиям pos_type в [iostreams.limits.pos] и [iostream.forward].
Члены двух аргументов assign, eqи lt должны быть определены тождественны встроенными операторами =, ==и < соответственно.
namespace std { 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; 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 char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static 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; }; }
Типu32streampos должен быть типом , определяемым реализацией, который удовлетворяет требованиям pos_type в [iostreams.limits.pos] и [iostream.forward].
Члены двух аргументов assign, eqи lt должны быть определены тождественны встроенными операторами =, ==и < соответственно.
namespace std { 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; 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 char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static 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; }; }
Определенные типы для int_type, pos_typeи state_type должны быть wint_t, wstreamposи mbstate_t соответственно.
Типwstreampos должен быть типом , определяемым реализацией, который удовлетворяет требованиям pos_type в [iostreams.limits.pos] и [iostream.forward].
Тип mbstate_t определяется <cwchar> и может представлять любое из состояний преобразования, которое может происходить в определяемом реализацией наборе поддерживаемых правил кодирования многобайтовых символов.
Члены двух аргументов assign, eqи lt должны быть определены тождественны встроенными операторами =, ==и < соответственно.
Заголовка <string> определяет basic_string шаблон класса для манипулирования переменной длины последовательности углеродно как объекты и четыре typedef-names, string, u16string, u32string, и wstring, что имя специализации basic_string<char>, basic_string<char16_t>, basic_string<char32_t>, и basic_string<wchar_t>, соответственно.
#include <initializer_list> namespace std { // [char.traits], character traits template<class charT> struct char_traits; template<> struct char_traits<char>; template<> struct char_traits<char16_t>; template<> struct char_traits<char32_t>; template<> struct char_traits<wchar_t>; // [basic.string], basic_string template<class charT, class traits = char_traits<charT>, class Allocator = allocator<charT>> class basic_string; template<class charT, class traits, class Allocator> 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> 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> 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> 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> basic_string<charT, traits, Allocator> operator+(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(const charT* lhs, basic_string<charT, traits, Allocator>&& rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(charT lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(charT lhs, basic_string<charT, traits, Allocator>&& rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(basic_string<charT, traits, Allocator>&& lhs, const charT* rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(const basic_string<charT, traits, Allocator>& lhs, charT rhs); template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(basic_string<charT, traits, Allocator>&& lhs, charT rhs); template<class charT, class traits, class Allocator> bool operator==(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept; template<class charT, class traits, class Allocator> bool operator==(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> bool operator==(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> bool operator!=(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept; template<class charT, class traits, class Allocator> bool operator!=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> bool operator!=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> bool operator< (const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept; template<class charT, class traits, class Allocator> bool operator< (const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> bool operator< (const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> bool operator> (const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept; template<class charT, class traits, class Allocator> bool operator> (const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> bool operator> (const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> bool operator<=(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept; template<class charT, class traits, class Allocator> bool operator<=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> bool operator<=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); template<class charT, class traits, class Allocator> bool operator>=(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept; template<class charT, class traits, class Allocator> bool operator>=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs); template<class charT, class traits, class Allocator> bool operator>=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs); // [string.special], swap template<class charT, class traits, class Allocator> void swap(basic_string<charT, traits, Allocator>& lhs, basic_string<charT, traits, Allocator>& rhs) noexcept(noexcept(lhs.swap(rhs))); // [string.io], 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); // basic_string typedef names using string = basic_string<char>; using u16string = basic_string<char16_t>; using u32string = basic_string<char32_t>; using wstring = basic_string<wchar_t>; // [string.conversions], numeric conversions int stoi(const string& str, size_t* idx = 0, int base = 10); long stol(const string& str, size_t* idx = 0, int base = 10); unsigned long stoul(const string& str, size_t* idx = 0, int base = 10); long long stoll(const string& str, size_t* idx = 0, int base = 10); unsigned long long stoull(const string& str, size_t* idx = 0, int base = 10); float stof(const string& str, size_t* idx = 0); double stod(const string& str, size_t* idx = 0); long double stold(const string& str, size_t* idx = 0); 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 = 0, int base = 10); long stol(const wstring& str, size_t* idx = 0, int base = 10); unsigned long stoul(const wstring& str, size_t* idx = 0, int base = 10); long long stoll(const wstring& str, size_t* idx = 0, int base = 10); unsigned long long stoull(const wstring& str, size_t* idx = 0, int base = 10); float stof(const wstring& str, size_t* idx = 0); double stod(const wstring& str, size_t* idx = 0); long double stold(const wstring& str, size_t* idx = 0); 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); // [basic.string.hash], hash support template<class T> struct hash; template<> struct hash<string>; template<> struct hash<u16string>; template<> struct hash<u32string>; template<> struct hash<wstring>; 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 u16string = basic_string<char16_t>; using u32string = basic_string<char32_t>; using wstring = basic_string<wchar_t>; } inline namespace literals { inline namespace string_literals { // [basic.string.literals], suffix for basic_string literals string operator""s(const char* str, size_t len); u16string operator""s(const char16_t* str, size_t len); u32string operator""s(const char32_t* str, size_t len); wstring operator""s(const wchar_t* str, size_t len); } } }
Шаблон класса basic_string описывает объекты, которые могут хранить последовательность, состоящую из переменного числа произвольных char-подобных объектов, с первым элементом последовательности в нулевой позиции. Такая последовательность также называется «строкой», если тип char-подобных объектов, которые она содержит, ясен из контекста. В остальной части этого раздела тип char-подобных объектов, содержащихся в basic_string объекте, обозначается с помощью charT.
Функции-члены basic_string используют объект Allocator класса, переданный в качестве параметра шаблона, для выделения и освобождения памяти для содержащихся в нем объектов типа char.225
Функции, описанные в этом пункте, могут сообщать о двух типах ошибок, каждый из которых связан с типом исключения:
length ошибка связана с исключениями типа length_error;
out-of-range ошибка связана с исключениями типа out_of_range.
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; // see [container.requirements] using const_iterator = implementation-defined; // see [container.requirements] using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; static const size_type npos = -1; // [string.cons], construct/copy/destroy basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { } explicit basic_string(const Allocator& a) noexcept; basic_string(const basic_string& str); basic_string(basic_string&& str) noexcept; basic_string(const basic_string& str, size_type pos, const Allocator& a = Allocator()); basic_string(const basic_string& str, size_type pos, size_type n, const Allocator& a = Allocator()); template<class T> basic_string(const T& t, size_type pos, size_type n, const Allocator& a = Allocator()); explicit basic_string(basic_string_view<charT, traits> sv, const Allocator& a = Allocator()); basic_string(const charT* s, size_type n, const Allocator& a = Allocator()); basic_string(const charT* s, const Allocator& a = Allocator()); basic_string(size_type n, charT c, const Allocator& a = Allocator()); template<class InputIterator> basic_string(InputIterator begin, InputIterator end, const Allocator& a = Allocator()); basic_string(initializer_list<charT>, const Allocator& = Allocator()); basic_string(const basic_string&, const Allocator&); basic_string(basic_string&&, const Allocator&); ~basic_string(); basic_string& operator=(const basic_string& str); basic_string& operator=(basic_string&& str) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value); basic_string& operator=(basic_string_view<charT, traits> sv); basic_string& operator=(const charT* s); basic_string& operator=(charT c); basic_string& operator=(initializer_list<charT>); // [string.iterators], 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; // [string.capacity], capacity size_type size() const noexcept; size_type length() const noexcept; size_type max_size() const noexcept; void resize(size_type n, charT c); void resize(size_type n); size_type capacity() const noexcept; void reserve(size_type res_arg = 0); void shrink_to_fit(); void clear() noexcept; bool empty() const noexcept; // [string.access], element access const_reference operator[](size_type pos) const; reference operator[](size_type pos); const_reference at(size_type n) const; reference at(size_type n); const charT& front() const; charT& front(); const charT& back() const; charT& back(); // [string.modifiers], modifiers basic_string& operator+=(const basic_string& str); basic_string& operator+=(basic_string_view<charT, traits> sv); basic_string& operator+=(const charT* s); basic_string& operator+=(charT c); basic_string& operator+=(initializer_list<charT>); basic_string& append(const basic_string& str); basic_string& append(const basic_string& str, size_type pos, size_type n = npos); basic_string& append(basic_string_view<charT, traits> sv); template<class T> basic_string& append(const T& t, size_type pos, size_type n = npos); basic_string& append(const charT* s, size_type n); basic_string& append(const charT* s); basic_string& append(size_type n, charT c); template<class InputIterator> basic_string& append(InputIterator first, InputIterator last); basic_string& append(initializer_list<charT>); void push_back(charT c); basic_string& assign(const basic_string& str); basic_string& assign(basic_string&& str) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value); basic_string& assign(const basic_string& str, size_type pos, size_type n = npos); basic_string& assign(basic_string_view<charT, traits> sv); template<class T> basic_string& assign(const T& t, size_type pos, size_type n = npos); basic_string& assign(const charT* s, size_type n); basic_string& assign(const charT* s); basic_string& assign(size_type n, charT c); template<class InputIterator> basic_string& assign(InputIterator first, InputIterator last); basic_string& assign(initializer_list<charT>); basic_string& insert(size_type pos, const basic_string& str); basic_string& insert(size_type pos1, const basic_string& str, size_type pos2, size_type n = npos); basic_string& insert(size_type pos, basic_string_view<charT, traits> sv); template<class T> basic_string& insert(size_type pos1, const T& t, size_type pos2, size_type n = npos); basic_string& insert(size_type pos, const charT* s, size_type n); basic_string& insert(size_type pos, const charT* s); basic_string& insert(size_type pos, size_type n, charT c); iterator insert(const_iterator p, charT c); iterator insert(const_iterator p, size_type n, charT c); template<class InputIterator> iterator insert(const_iterator p, InputIterator first, InputIterator last); iterator insert(const_iterator p, initializer_list<charT>); basic_string& erase(size_type pos = 0, size_type n = npos); iterator erase(const_iterator p); iterator erase(const_iterator first, const_iterator last); void pop_back(); basic_string& replace(size_type pos1, size_type n1, const basic_string& str); basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2 = npos); basic_string& replace(size_type pos1, size_type n1, basic_string_view<charT, traits> sv); template<class T> basic_string& replace(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos); basic_string& replace(size_type pos, size_type n1, const charT* s, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s); basic_string& replace(size_type pos, size_type n1, size_type n2, charT c); basic_string& replace(const_iterator i1, const_iterator i2, const basic_string& str); basic_string& replace(const_iterator i1, const_iterator i2, basic_string_view<charT, traits> sv); basic_string& replace(const_iterator i1, const_iterator i2, const charT* s, size_type n); basic_string& replace(const_iterator i1, const_iterator i2, const charT* s); basic_string& replace(const_iterator i1, const_iterator i2, size_type n, charT c); template<class InputIterator> basic_string& replace(const_iterator i1, const_iterator i2, InputIterator j1, InputIterator j2); basic_string& replace(const_iterator, const_iterator, initializer_list<charT>); size_type copy(charT* s, size_type n, size_type pos = 0) const; void swap(basic_string& str) noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value || allocator_traits<Allocator>::is_always_equal::value); // [string.ops], string operations const charT* c_str() const noexcept; const charT* data() const noexcept; charT* data() noexcept; operator basic_string_view<charT, traits>() const noexcept; allocator_type get_allocator() const noexcept; size_type find (basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept; size_type find (const basic_string& str, size_type pos = 0) const noexcept; size_type find (const charT* s, size_type pos, size_type n) const; size_type find (const charT* s, size_type pos = 0) const; size_type find (charT c, size_type pos = 0) const; size_type rfind(basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept; size_type rfind(const basic_string& str, size_type pos = npos) const noexcept; size_type rfind(const charT* s, size_type pos, size_type n) const; size_type rfind(const charT* s, size_type pos = npos) const; size_type rfind(charT c, size_type pos = npos) const; size_type find_first_of(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept; size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept; size_type find_first_of(const charT* s, size_type pos, size_type n) const; size_type find_first_of(const charT* s, size_type pos = 0) const; size_type find_first_of(charT c, size_type pos = 0) const; size_type find_last_of (basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept; size_type find_last_of (const basic_string& str, size_type pos = npos) const noexcept; size_type find_last_of (const charT* s, size_type pos, size_type n) const; size_type find_last_of (const charT* s, size_type pos = npos) const; size_type find_last_of (charT c, size_type pos = npos) const; size_type find_first_not_of(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept; size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept; size_type find_first_not_of(const charT* s, size_type pos, size_type n) const; size_type find_first_not_of(const charT* s, size_type pos = 0) const; size_type find_first_not_of(charT c, size_type pos = 0) const; size_type find_last_not_of (basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept; size_type find_last_not_of (const basic_string& str, size_type pos = npos) const noexcept; size_type find_last_not_of (const charT* s, size_type pos, size_type n) const; size_type find_last_not_of (const charT* s, size_type pos = npos) const; size_type find_last_not_of (charT c, size_type pos = npos) const; basic_string substr(size_type pos = 0, size_type n = npos) const; int compare(basic_string_view<charT, traits> sv) const noexcept; int compare(size_type pos1, size_type n1, basic_string_view<charT, traits> sv) const; template<class T> int compare(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos) const; int compare(const basic_string& str) const noexcept; int compare(size_type pos1, size_type n1, const basic_string& str) const; int compare(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2 = npos) const; int compare(const charT* s) const; int compare(size_type pos1, size_type n1, const charT* s) const; int compare(size_type pos1, size_type n1, const charT* s, size_type n2) const; }; template<class InputIterator, class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>> basic_string(InputIterator, InputIterator, Allocator = Allocator()) -> basic_string<typename iterator_traits<InputIterator>::value_type, char_traits<typename iterator_traits<InputIterator>::value_type>, Allocator>; }
Allocator::value_type должен называть тот же тип, что и charT ([string.require]).
Если какая-либо операция вызовет size() превышение max_size(), эта операция вызовет объект исключения типа length_error.
Если какая-либо функция-член или оператор basic_string выдает исключение, эта функция или оператор не должны иметь никакого другого эффекта.
В каждой специализации basic_string<charT, traits, Allocator>тип allocator_traits<Allocator>::value_type должен называть тот же тип, что и charT. Каждый объект типа basic_string<charT, traits, Allocator> должен использовать объект типа Allocator для выделения и освобождения памяти для содержащихся charT объектов по мере необходимости. Используемый Allocator объект должен быть получен, как описано в [container.requirements.general]. В каждой специализации basic_string<charT, traits, Allocator>тип traits должен удовлетворять требованиям к характеристикам символов ([char.traits]), и тип traits::char_type должен называть тот же тип, что и charT.
Ссылки, указатели и итераторы, относящиеся к элементам basic_string последовательности, могут быть признаны недействительными при следующих применениях этого basic_string объекта:
в качестве аргумента любой стандартной библиотечной функции, принимающейbasic_string в качестве аргумента ссылку на неконстантный .226
Вызов неконстантная функций - членов, за исключением operator[], at, data, front, back, begin, rbegin, end, и rend.
Например, в качестве аргумента для функций swap(), не являющихся членамиoperator>>(), и getline(), или в качестве аргумента для basic_string::swap().
explicit basic_string(const Allocator& a) noexcept;
basic_string(const basic_string& str);
basic_string(basic_string&& str) noexcept;
Effects: Создает объект класса, basic_string как указано в Табл 56. Во второй форме str остается в допустимом состоянии с неопределенным значением.
Элемент | Ценить |
data() | указывает на первый элемент выделенной копии массива, на первый элемент которого указывает str.data() |
size() | str.size() |
capacity() | значение, по крайней мере, такое большое, как size() |
basic_string(const basic_string& str, size_type pos,
const Allocator& a = Allocator());
basic_string(const basic_string& str, size_type pos, size_type n,
const Allocator& a = Allocator());
Effects: Создает объект класса basic_string и определяет эффективную длину rlen начального строкового значения как меньшее из n и str.size() - pos, как указано в таблице 57.
Элемент | Ценить |
data() | указывает на первый элемент выделенной копии rlen последовательных элементов строки, управляемой str начиная с позиции pos |
size() | rlen |
capacity() | значение, по крайней мере, такое большое, как size() |
template<class T>
basic_string(const T& t, size_type pos, size_type n,
const Allocator& a = Allocator());
Effects: Создает переменную, svкак если бы by, basic_string_view<charT, traits> sv = t; а затем ведет себя так же, как:
basic_string(sv.substr(pos, n), a);
Remarks: Этот конструктор не должен участвовать в разрешении перегрузки , если is_convertible_v<const T&, basic_string_view<charT, traits>> не true.
explicit basic_string(basic_string_view<charT, traits> sv,
const Allocator& a = Allocator());
basic_string(const charT* s, size_type n,
const Allocator& a = Allocator());
Effects: Создает объект класса basic_string и определяет его начальное строковое значение из массива charT длины n , первый элемент которого обозначен s, как указано в таблице 58.
Элемент | Ценить |
data() | указывает на первый элемент выделенной копии массива, на первый элемент которого указывает s |
size() | n |
capacity() | значение, по крайней мере, такое большое, как size() |
basic_string(const charT* s, const Allocator& a = Allocator());
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
Effects: Создает объект класса basic_string и определяет его начальное строковое значение из массива charT длины traits::length(s) , первый элемент которого обозначен s, как указано в таблице 59.
Элемент | Ценить |
data() | указывает на первый элемент выделенной копии массива, на первый элемент которого указывает s |
size() | traits::length(s) |
capacity() | значение, по крайней мере, такое большое, как size() |
basic_string(size_type n, charT c, const Allocator& a = Allocator());
Effects: Создает объект класса basic_string и определяет его начальное строковое значение, повторяя объект типа char c для всех n элементов, как указано в таблице 60.
Элемент | Ценить |
data() | указывает на первый элемент выделенного массива n элементов, каждый из которых хранит начальное значение c |
size() | n |
capacity() | значение, по крайней мере, такое большое, как size() |
template<class InputIterator>
basic_string(InputIterator begin, InputIterator end,
const Allocator& a = Allocator());
Effects: Если InputIterator это целочисленный тип, эквивалентный:
basic_string(static_cast<size_type>(begin), static_cast<value_type>(end), a);
В противном случае создает строку из значений в диапазоне [begin, end), как указано в таблице требований к последовательности (см. [sequence.reqmts]).
basic_string(initializer_list<charT> il, const Allocator& a = Allocator());
basic_string(const basic_string& str, const Allocator& alloc);
basic_string(basic_string&& str, const Allocator& alloc);
Effects: Создает объект класса, basic_string как указано в Табл 61. Сохраненный распределитель построен из alloc. Во второй форме str остается в допустимом состоянии с неопределенным значением.
Элемент | Ценить |
data() | указывает на первый элемент выделенной копии массива, на первый элемент которого указывает исходное значение str.data(). |
size() | первоначальная стоимость str.size() |
capacity() | значение, по крайней мере, такое большое, как size() |
get_allocator() | alloc |
template<class InputIterator,
class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
basic_string(InputIterator, InputIterator, Allocator = Allocator())
-> basic_string<typename iterator_traits<InputIterator>::value_type,
char_traits<typename iterator_traits<InputIterator>::value_type>,
Allocator>;
Remarks: Не должен участвовать в разрешении перегрузки, если InputIterator это тип, который не квалифицируется как итератор ввода, или если Allocator это тип, который не квалифицируется как распределитель ([container.requirements.general]).
basic_string& operator=(const basic_string& str);
basic_string& operator=(basic_string&& str)
noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||
allocator_traits<Allocator>::is_always_equal::value);
Effects: Перемещение присваивается как a sequence container, за исключением того, что итераторы, указатели и ссылки могут быть недействительными.
basic_string& operator=(basic_string_view<charT, traits> sv);
basic_string& operator=(const charT* s);
basic_string& operator=(charT c);
basic_string& operator=(initializer_list<charT> il);
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
const_reverse_iterator crbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_reverse_iterator crend() const noexcept;
size_type size() const noexcept;
size_type length() const noexcept;
size_type max_size() const noexcept;
Returns: Максимально возможное количество символьных объектов, которые могут храниться в basic_string.
void resize(size_type n, charT c);
Effects: Изменяет длину строки, обозначенной *this следующим образом:
Если n <= size()функция заменяет строку, обозначенную знаком, *this строкой длины n , элементы которой являются копией начальных элементов исходной строки, обозначенной *this.
Если n > size(), функция заменяет строку, обозначенную *this с помощью, строкой длины n , первые size() элементы которой являются копией исходной строки, обозначенной с помощью *this, а остальные элементы которой инициализируются c.
void resize(size_type n);
size_type capacity() const noexcept;
void reserve(size_type res_arg=0);
Функция-член reserve() - это директива, информирующая basic_string объект о запланированном изменении размера, чтобы он мог соответствующим образом управлять распределением хранилища.
Effects: После тогоreserve(), capacity() больше или равен аргумент reserve. [ Note: Вызов reserve() с res_arg аргументом, меньшим чем capacity() , по сути, является необязательным запросом на сжатие. Обращение с помощью res_arg <= size() по сути является необязательным запросом на усадку по размеру. ] — end note
void shrink_to_fit();
Effects: shrink_to_fit является необязательным запросом для сокращения capacity() до size(). [ Note: Запрос не является обязывающим, чтобы дать свободу для оптимизации, зависящей от реализации. ] Он не увеличивается , но может уменьшаться , вызывая перераспределение. — end note capacity() capacity()
Remarks: Перераспределение делает недействительными все ссылки, указатели и итераторы, относящиеся к элементам в последовательности, а также к итератору, прошедшему конец. Если перераспределения не происходит, они остаются в силе.
void clear() noexcept;
bool empty() const noexcept;
reserve() использования, allocator_traits<Allocator>::allocate() которые могут вызвать соответствующее исключение.
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Returns: *(begin() + pos) если pos < size(). В противном случае возвращает ссылку на объект типа charT со значением charT(), где изменение объекта на любое значение, кроме charT() приводит к неопределенному поведению.
const_reference at(size_type pos) const;
reference at(size_type pos);
const charT& front() const;
charT& front();
const charT& back() const;
charT& back();
basic_string&
operator+=(const basic_string& str);
basic_string& operator+=(basic_string_view<charT, traits> sv);
basic_string& operator+=(const charT* s);
basic_string& operator+=(charT c);
basic_string& operator+=(initializer_list<charT> il);
basic_string&
append(const basic_string& str);
basic_string&
append(const basic_string& str, size_type pos, size_type n = npos);
Effects: Определяет эффективную длину rlen добавляемой строки как меньшее из вызовов n и str.size() - pos и append(str.data() + pos, rlen).
basic_string& append(basic_string_view<charT, traits> sv);
template<class T>
basic_string& append(const T& t, size_type pos, size_type n = npos);
Effects: Создает переменную sv, как будто by basic_string_view<charT, traits> sv = t. Определяет эффективную длину rlen добавляемой строки как меньшее из вызовов n и sv.size() - posи append(sv.data() + pos, rlen).
Remarks: Эта функция не будет участвовать в разрешении перегрузки , если is_convertible_v<const T&, basic_string_view<charT, traits>> не true и is_convertible_v<const T&, const charT*> является false.
basic_string&
append(const charT* s, size_type n);
Effects: Функция заменяет строку, которой управляет, *this строкой длины size() + n , первые size() элементы которой являются копией исходной строки, которой управляет, *this а остальные элементы - копией начальных n элементов s.
basic_string& append(const charT* s);
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
basic_string& append(size_type n, charT c);
template<class InputIterator>
basic_string& append(InputIterator first, InputIterator last);
basic_string& append(initializer_list<charT> il);
void push_back(charT c);
basic_string& assign(const basic_string& str);
basic_string& assign(basic_string&& str)
noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||
allocator_traits<Allocator>::is_always_equal::value);
basic_string&
assign(const basic_string& str, size_type pos,
size_type n = npos);
Effects: Определяет эффективную длину rlen строки, которая назначается как меньшее из вызовов n и str.size() - pos и assign(str.data() + pos, rlen).
basic_string& assign(basic_string_view<charT, traits> sv);
template<class T>
basic_string& assign(const T& t, size_type pos, size_type n = npos);
Effects: Создает переменную sv, как будто by basic_string_view<charT, traits> sv = t. Определяет эффективную длину rlen строки, которая назначается как меньшее из вызовов n и sv.size() - posи assign(sv.data() + pos, rlen).
Remarks: Эта функция не будет участвовать в разрешении перегрузки , если is_convertible_v<const T&, basic_string_view<charT, traits>> не true и is_convertible_v<const T&, const charT*> является false.
basic_string& assign(const charT* s, size_type n);
Effects: Заменяет строку, управляемую *this с помощью, строкой длины n , элементы которой являются копией тех, на которые указывает s.
basic_string& assign(const charT* s);
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
basic_string& assign(initializer_list<charT> il);
basic_string& assign(size_type n, charT c);
template<class InputIterator>
basic_string& assign(InputIterator first, InputIterator last);
basic_string&
insert(size_type pos,
const basic_string& str);
basic_string&
insert(size_type pos1,
const basic_string& str,
size_type pos2, size_type n = npos);
Effects: Определяет эффективную длину rlen строки для вставки в качестве меньшего из вызовов n и str.size() - pos2 и insert(pos1, str.data() + pos2, rlen).
basic_string& insert(size_type pos, basic_string_view<charT, traits> sv);
template<class T>
basic_string& insert(size_type pos1, const T& t,
size_type pos2, size_type n = npos);
Effects: Создает переменную sv, как будто by basic_string_view<charT, traits> sv = t. Определяет эффективную длину rlen строки, которая назначается как меньшее из вызовов n и sv.size() - pos2и insert(pos1, sv.data() + pos2, rlen).
Remarks: Эта функция не будет участвовать в разрешении перегрузки , если is_convertible_v<const T&, basic_string_view<charT, traits>> не true и is_convertible_v<const T&, const charT*> является false.
basic_string&
insert(size_type pos, const charT* s, size_type n);
Effects: Заменяет строку, управляемую *this строкой длины size() + n , первые pos элементы которой являются копией начальных элементов исходной строки, которой управляет, *this и чьи следующие n элементы являются копией элементов в, s а остальные элементы являются копией остальных элементов исходная строка, управляемая *this.
basic_string&
insert(size_type pos, const charT* s);
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
basic_string&
insert(size_type pos, size_type n, charT c);
iterator insert(const_iterator p, charT c);
iterator insert(const_iterator p, size_type n, charT c);
template<class InputIterator>
iterator insert(const_iterator p, InputIterator first, InputIterator last);
Returns: Итератор, который ссылается на копию первого вставленного символа, или p если first == last.
iterator insert(const_iterator p, initializer_list<charT> il);
basic_string& erase(size_type pos = 0, size_type n = npos);
Effects: Определяет эффективную длину xlen удаляемой строки как меньшее из значений n и size() - pos.
Затем функция заменяет строку, управляемую *this с помощью строки длины size() - xlen , первые pos элементы которой являются копией начальных элементов исходной строки, которой управляет *this, а остальные элементы которой являются копией элементов исходной строки, управляемой *this начиная с позиции pos + xlen.
iterator erase(const_iterator p);
Returns: Итератор, который указывает на элемент, следующий непосредственно за p стираемым элементом. Если такого элемента не существует, end() возвращается.
iterator erase(const_iterator first, const_iterator last);
Requires: first и last являются действительными итераторами *this, определяющими диапазон [first, last).
Returns: Итератор, который указывает на элемент, на который указывает до last удаления других элементов. Если такого элемента не существует, end() возвращается.
void pop_back();
basic_string&
replace(size_type pos1, size_type n1,
const basic_string& str);
basic_string&
replace(size_type pos1, size_type n1,
const basic_string& str,
size_type pos2, size_type n2 = npos);
Effects: Определяет эффективную длину rlen вставляемой строки как меньшее из вызовов n2 и str.size() - pos2 и replace(pos1, n1, str.data() + pos2, rlen).
basic_string& replace(size_type pos1, size_type n1,
basic_string_view<charT, traits> sv);
template<class T>
basic_string& replace(size_type pos1, size_type n1, const T& t,
size_type pos2, size_type n2 = npos);
Effects: Создает переменную sv, как будто by basic_string_view<charT, traits> sv = t. Определяет эффективную длину rlen вставляемой строки как меньшее из вызовов n2 и sv.size() - pos2и replace(pos1, n1, sv.data() + pos2, rlen).
Remarks: Эта функция не будет участвовать в разрешении перегрузки , если is_convertible_v<const T&, basic_string_view<charT, traits>> не true и is_convertible_v<const T&, const charT*> является false.
basic_string&
replace(size_type pos1, size_type n1, const charT* s, size_type n2);
Throws: out_of_range если pos1 > size() или length_error если длина результирующей строки превысит max_size() (см. ниже).
Effects: Определяет эффективную длину xlen удаляемой строки как меньшее из значений n1 и size() - pos1. Если size() - xlen >= max_size() - n2 кидает length_error. В противном случае функция заменяет строку, управляемую символом *,this строкой длины size() - xlen + n2 , первые pos1 элементы которой являются копией начальных элементов исходной строки *this, которой управляет , чьи следующие n2 элементы являются копией начальных n2 элементов s, а остальные элементы - копия элементов исходной строки, управляемая *this начиная с позиции pos + xlen.
basic_string&
replace(size_type pos, size_type n, const charT* s);
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
basic_string&
replace(size_type pos1, size_type n1,
size_type n2, charT c);
basic_string& replace(const_iterator i1, const_iterator i2, const basic_string& str);
basic_string& replace(const_iterator i1, const_iterator i2,
basic_string_view<charT, traits> sv);
basic_string&
replace(const_iterator i1, const_iterator i2, const charT* s, size_type n);
Requires: [begin(), i1) и [i1, i2) являются допустимыми диапазонами и s указывают на массив, состоящий как минимум из n элементов charT.
basic_string& replace(const_iterator i1, const_iterator i2, const charT* s);
Requires: [begin(), i1) и [i1, i2) являются допустимыми диапазонами и s указывают на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
basic_string& replace(const_iterator i1, const_iterator i2, size_type n,
charT c);
template<class InputIterator>
basic_string& replace(const_iterator i1, const_iterator i2,
InputIterator j1, InputIterator j2);
basic_string& replace(const_iterator i1, const_iterator i2,
initializer_list<charT> il);
size_type copy(charT* s, size_type n, size_type pos = 0) const;
Effects: Эквивалент: traits::copy(s, data() + pos, rlen). [ Note: Это не заканчивается s нулевым объектом. ] — end note
void swap(basic_string& s)
noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value ||
allocator_traits<Allocator>::is_always_equal::value);
Postconditions: *this содержит ту же последовательность символов, которая была в s, s содержит ту же последовательность символов, что была в *this.
const charT* c_str() const noexcept;
const charT* data() const noexcept;
charT* data() noexcept;
operator basic_string_view<charT, traits>() const noexcept;
allocator_type get_allocator() const noexcept;
size_type find(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
size_type find(const basic_string& str, size_type pos = 0) const noexcept;
size_type find(const charT* s, size_type pos, size_type n) const;
size_type find(const charT* s, size_type pos = 0) const;
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
size_type find(charT c, size_type pos = 0) const;
size_type rfind(basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;
size_type rfind(const charT* s, size_type pos, size_type n) const;
size_type rfind(const charT* s, size_type pos = npos) const;
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
size_type rfind(charT c, size_type pos = npos) const;
size_type find_first_of(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;
size_type find_first_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_of(const charT* s, size_type pos = 0) const;
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
size_type find_first_of(charT c, size_type pos = 0) const;
size_type find_last_of(basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept;
size_type find_last_of(const charT* s, size_type pos, size_type n) const;
size_type find_last_of(const charT* s, size_type pos = npos) const;
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
size_type find_last_of(charT c, size_type pos = npos) const;
size_type find_first_not_of(basic_string_view<charT, traits> sv,
size_type pos = 0) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;
size_type find_first_not_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_not_of(const charT* s, size_type pos = 0) const;
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
size_type find_first_not_of(charT c, size_type pos = 0) const;
size_type find_last_not_of(basic_string_view<charT, traits> sv,
size_type pos = npos) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept;
size_type find_last_not_of(const charT* s, size_type pos, size_type n) const;
size_type find_last_not_of(const charT* s, size_type pos = npos) const;
Requires: s указывает на массив, состоящий как минимум из traits::length(s) + 1 элементов charT.
size_type find_last_not_of(charT c, size_type pos = npos) const;
basic_string substr(size_type pos = 0, size_type n = npos) const;
Effects: Определяет эффективную длину rlen копируемой строки как меньшее из значений n и size() - pos.
int compare(basic_string_view<charT, traits> sv) const noexcept;
Effects: Определяет эффективную длину rlen строк для сравнения как меньшее из значений size() и sv.size(). Затем функция сравнивает две строки, вызывая traits::compare(data(), sv.data(), rlen).
int compare(size_type pos1, size_type n1, basic_string_view<charT, traits> sv) const;
Effects: Эквивалентно:
return basic_string_view<charT, traits>(data(), size()).substr(pos1, n1).compare(sv);
template<class T>
int compare(size_type pos1, size_type n1, const T& t,
size_type pos2, size_type n2 = npos) const;
Effects: Эквивалентно:
basic_string_view<charT, traits> sv = t; return basic_string_view<charT, traits>( data(), size()).substr(pos1, n1).compare(sv.substr(pos2, n2));
Remarks: Эта функция не будет участвовать в разрешении перегрузки , если is_convertible_v<const T&, basic_string_view<charT, traits>> не true и is_convertible_v<const T&, const charT*> является false.
int compare(const basic_string& str) const noexcept;
int compare(size_type pos1, size_type n1, const basic_string& str) const;
int compare(size_type pos1, size_type n1,
const basic_string& str,
size_type pos2, size_type n2 = npos) const;
int compare(const charT* s) const;
int compare(size_type pos, size_type n1, const charT* s) const;
int compare(size_type pos, size_type n1, const charT* s, size_type n2) const;
template<class charT, class traits, class Allocator>
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>
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>
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>
basic_string<charT, traits, Allocator>
operator+(basic_string<charT, traits, Allocator>&& lhs,
basic_string<charT, traits, Allocator>&& rhs);
Returns: std::move(lhs.append(rhs)). [ Note: Или то же самое, std::move(rhs.insert(0, lhs)). ] — end note
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const charT* lhs,
basic_string<charT, traits, Allocator>&& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(charT lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(charT lhs,
basic_string<charT, traits, Allocator>&& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(basic_string<charT, traits, Allocator>&& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const basic_string<charT, traits, Allocator>& lhs,
charT rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(basic_string<charT, traits, Allocator>&& lhs,
charT rhs);
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator==(const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
Requires: rhs указывает на массив, состоящий как минимум из traits::length(rhs) + 1 элементов charT.
template<class charT, class traits, class Allocator>
bool operator!=(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator!=(const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator!=(const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
Requires: rhs указывает на массив, состоящий как минимум из traits::length(rhs) + 1 элементов charT.
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator< (const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator> (const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator> (const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator> (const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator<=(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator<=(const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator<=(const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator>=(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator>=(const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator>=(const basic_string<charT, traits, Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
void swap(basic_string<charT, traits, Allocator>& lhs,
basic_string<charT, traits, Allocator>& rhs)
noexcept(noexcept(lhs.swap(rhs)));
template<class charT, class traits, class Allocator>
basic_istream<charT, traits>&
operator>>(basic_istream<charT, traits>& is,
basic_string<charT, traits, Allocator>& str);
Effects: Ведет себя как formatted input function. После создания sentry объекта, если часовой преобразуется в true, вызывает, str.erase() а затем извлекает символы из is и добавляет их, str как если бы, вызывая str.append(1, c). Если is.width() больше нуля, максимальное количество n добавляемых символов is.width(): в противном случае n это str.max_size(). Символы извлекаются и добавляются до тех пор, пока не произойдет одно из следующих событий:
n символы сохраняются;
конец файла встречается во входной последовательности;
isspace(c, is.getloc()) является true для следующего доступного входного символа c.
После извлечения последнего символа (если есть) вызывается is.width(0) и sentry объект уничтожается.
Если функция не извлекает символы, она вызывает is.setstate(ios::failbit), что может вызвать throw ios_base::failure ([iostate.flags]).
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);
Effects: Ведет себя как объект unformatted input function, за исключением того, что не влияет на значение, возвращаемое при последующих вызовах basic_istream<>::gcount(). После создания sentry объекта, если часовой преобразуется в true, вызывает, str.erase() а затем извлекает символы is и добавляет их, str как если бы, вызывая str.append(1, c) до тех пор, пока не произойдет одно из следующих событий:
конец файла происходит во входной последовательности (в этом случае getline вызывается функция is.setstate(ios_base::eofbit)).
traits::eq(c, delim) для следующего доступного входного символа c (в этом случае c извлекается, но не добавляется) ([iostate.flags])
str.max_size() символы сохраняются (в этом случае функция calls is.setstate(ios_base::failbit)) ([iostate.flags])
Условия проверяются в указанном порядке. В любом случае после извлечения последнего символа sentry объект уничтожается.
Если функция не извлекает символы, она вызывает is.setstate(ios_base::failbit) which may throw ios_base::failure ([iostate.flags]).
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);
int stoi(const string& str, size_t* idx = 0, int base = 10);
long stol(const string& str, size_t* idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t* idx = 0, int base = 10);
long long stoll(const string& str, size_t* idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t* idx = 0, int base = 10);
Effects: первые два вызова функций strtol(str.c_str(), ptr, base), а последние три вызова функций strtoul(str.c_str(), ptr, base), strtoll(str.c_str(), ptr, base)и strtoull(str.c_str(), ptr, base), соответственно. Каждая функция возвращает преобразованный результат, если таковой имеется. Аргумент ptr обозначает указатель на объект, внутренний по отношению к функции, который используется для определения того, что хранить *idx. Если функция не генерирует исключение и idx != 0, функция сохраняет *idx индекс первого неконвертированного элемента str.
Throws: invalid_argument если strtol, strtoul, strtoll, или strtoull сообщает , что преобразование не может быть выполнено. Выдает , out_of_range если strtol, strtoul, strtoll или strtoull множества , errno чтобы ERANGE, или если преобразованное значение находится вне диапазона представимых значений для типа возврата.
float stof(const string& str, size_t* idx = 0);
double stod(const string& str, size_t* idx = 0);
long double stold(const string& str, size_t* idx = 0);
Effects: Эти функции называют strtof(str.c_str(), ptr), strtod(str.c_str(), ptr)и strtold(str.c_str(), ptr), соответственно. Каждая функция возвращает преобразованный результат, если таковой имеется. Аргумент ptr обозначает указатель на объект, внутренний по отношению к функции, который используется для определения того, что хранить *idx. Если функция не генерирует исключение и idx != 0, функция сохраняет *idx индекс первого неконвертированного элемента str.
Throws: invalid_argument если strtof, strtodили strtold сообщает , что преобразование не может быть выполнено. Выдает ,out_of_range если strtof, strtodили strtold наборы , errno чтобы ERANGE или если преобразованное значение находится вне диапазона представимых значений для типа возврата.
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);
Returns: Каждая функция возвращает string объект , содержащий символьное представление значения его аргумента , который будет сгенерирован путем вызова sprintf(buf, fmt, val) с спецификатора форматом из "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", или "%Lf", соответственно, где buf обозначает внутренний буфер символов достаточного размера.
int stoi(const wstring& str, size_t* idx = 0, int base = 10);
long stol(const wstring& str, size_t* idx = 0, int base = 10);
unsigned long stoul(const wstring& str, size_t* idx = 0, int base = 10);
long long stoll(const wstring& str, size_t* idx = 0, int base = 10);
unsigned long long stoull(const wstring& str, size_t* idx = 0, int base = 10);
Effects: первые два вызова функций wcstol(str.c_str(), ptr, base), а последние три вызова функций wcstoul(str.c_str(), ptr, base), wcstoll(str.c_str(), ptr, base)и wcstoull(str.c_str(), ptr, base), соответственно. Каждая функция возвращает преобразованный результат, если таковой имеется. Аргумент ptr обозначает указатель на объект, внутренний по отношению к функции, который используется для определения того, что хранить *idx. Если функция не генерирует исключение и idx != 0, функция сохраняет *idx индекс первого неконвертированного элемента str.
Throws: invalid_argument если wcstol, wcstoul, wcstoll, или wcstoull сообщает , что преобразование не может быть выполнено. Выбрасывается, out_of_range если преобразованное значение выходит за пределы диапазона представимых значений для возвращаемого типа.
float stof(const wstring& str, size_t* idx = 0);
double stod(const wstring& str, size_t* idx = 0);
long double stold(const wstring& str, size_t* idx = 0);
Effects: Эти функции называют wcstof(str.c_str(), ptr), wcstod(str.c_str(), ptr)и wcstold(str.c_str(), ptr), соответственно. Каждая функция возвращает преобразованный результат, если таковой имеется. Аргумент ptr обозначает указатель на объект, внутренний по отношению к функции, который используется для определения того, что хранить *idx. Если функция не генерирует исключение и idx != 0, функция сохраняет *idx индекс первого неконвертированного элемента str.
Throws: invalid_argument если wcstof, wcstodили wcstold сообщает , что преобразование не может быть выполнено. Выбрасывает out_of_range if wcstof, wcstodили wcstold устанавливает errno значение ERANGE.
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);
Returns: Каждая функция возвращает wstring объект , содержащий символьное представление значения его аргумента , который будет сгенерирован путем вызова swprintf(buf, buffsz, fmt, val) с спецификатора форматом из L"%d", L"%u", L"%ld", L"%lu", L"%lld", L"%llu", L"%f", L"%f", или L"%Lf", соответственно, где buf обозначает внутренний буфер символов достаточного размера buffsz.
template<> struct hash<string>;
template<> struct hash<u16string>;
template<> struct hash<u32string>;
template<> struct hash<wstring>;
string operator""s(const char* str, size_t len);
u16string operator""s(const char16_t* str, size_t len);
u32string operator""s(const char32_t* str, size_t len);
wstring operator""s(const wchar_t* str, size_t len);
Шаблон класса basic_string_view описывает объект, который может ссылаться на постоянную непрерывную последовательность char-like objects с первым элементом последовательности в нулевой позиции. В остальной части этого раздела тип char-подобных объектов, содержащихся в basic_string_view объекте, обозначается с помощью charT.
[ Note: Библиотека обеспечивает неявное преобразование из const charT* и std::basic_string<charT, ...> в, std::basic_string_view<charT, ...> чтобы пользовательский код мог принимать std::basic_string_view<charT> как параметр, не являющийся шаблоном, везде, где ожидается последовательность символов. Пользовательские типы должны определять свои собственные неявные преобразования std::basic_string_view в, чтобы взаимодействовать с этими функциями. ] — end note
namespace std { // [string.view.template], class template basic_string_view template<class charT, class traits = char_traits<charT>> class basic_string_view; // [string.view.comparison], 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 bool operator!=(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept; 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 bool operator> (basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept; 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 bool operator>=(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept; // see [string.view.comparison], sufficient additional overloads of comparison functions // [string.view.io], 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 u16string_view = basic_string_view<char16_t>; using u32string_view = basic_string_view<char32_t>; using wstring_view = basic_string_view<wchar_t>; // [string.view.hash], hash support template<class T> struct hash; template<> struct hash<string_view>; template<> struct hash<u16string_view>; template<> struct hash<u32string_view>; template<> struct hash<wstring_view>; inline namespace literals { inline namespace string_view_literals { // [string.view.literals], suffix for basic_string_view literals constexpr string_view operator""sv(const char* 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; } } }
Шаблоны функций, определенные в [utility.swap] и [iterator.range] доступны, если они <string_view> включены.
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; // see [string.view.iterators] using iterator = const_iterator;228 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); // [string.view.cons], 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(const charT* str, size_type len); // [string.view.iterators], 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; // [string.view.capacity], capacity constexpr size_type size() const noexcept; constexpr size_type length() const noexcept; constexpr size_type max_size() const noexcept; constexpr bool empty() const noexcept; // [string.view.access], 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; // [string.view.modifiers], modifiers constexpr void remove_prefix(size_type n); constexpr void remove_suffix(size_type n); constexpr void swap(basic_string_view& s) noexcept; // [string.view.ops], string operations 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 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 };
В каждой специализации basic_string_view<charT, traits>тип traits должен удовлетворять требованиям к характеристикам символов ([char.traits]), и тип traits::char_type должен называть тот же тип, что и charT.
Потому что basic_string_view относится к постоянной последовательности iterator и const_iterator относятся к одному типу.
constexpr basic_string_view() noexcept;
constexpr basic_string_view(const charT* str);
constexpr basic_string_view(const charT* str, size_type len);
using const_iterator = implementation-defined;
Тип, отвечающий требованиям постоянного итератора произвольного доступа ([random.access.iterators]) и непрерывного итератора ([iterator.requirements.general]), который value_type является параметром шаблона charT.
Для a basic_string_view strлюбая операция, которая делает недействительным указатель в диапазоне, [str.data(), str.data() + str.size()) делает недействительными указатели, итераторы и ссылки, возвращаемые из strметодов.
Все требования к контейнерным итераторам ([container.requirements]) также применимы basic_string_view::const_iterator .
constexpr const_iterator begin() const noexcept;
constexpr const_iterator cbegin() const noexcept;
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
constexpr const_reverse_iterator rbegin() const noexcept;
constexpr const_reverse_iterator crbegin() const noexcept;
constexpr const_reverse_iterator rend() const noexcept;
constexpr const_reverse_iterator crend() const noexcept;
constexpr size_type size() const noexcept;
constexpr size_type length() const noexcept;
constexpr size_type max_size() const noexcept;
Returns: Максимально возможное количество символьных объектов, на которые может ссылаться a basic_string_view.
constexpr bool empty() const noexcept;
constexpr const_reference operator[](size_type pos) const;
[ Note: В отличие от basic_string::operator[], basic_string_view::operator[](size()) имеет неопределенное поведение вместо возврата charT(). ] — end note
constexpr const_reference at(size_type pos) const;
constexpr const_reference front() const;
constexpr const_reference back() const;
constexpr const_pointer data() const noexcept;
constexpr void remove_prefix(size_type n);
constexpr void remove_suffix(size_type n);
constexpr void swap(basic_string_view& s) noexcept;
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 str) const noexcept;
Effects: Определяет rlenэффективную длину сравниваемых строк. Затем функция сравнивает две строки, вызывая traits::compare(data(), str.data(), rlen).
constexpr int compare(size_type pos1, size_type n1, basic_string_view str) const;
constexpr int compare(size_type pos1, size_type n1, basic_string_view str,
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;
В этом разделе описываются basic_string_view функции - члены с именем find, rfind, find_first_of, find_last_of, find_first_not_of, и find_last_not_of.
Функции-члены в этом разделе O(size() * str.size()) в худшем случае сложны, хотя реализациям рекомендуется работать лучше.
Каждая функция-член формы
constexpr return-type F(const charT* s, size_type pos);
эквивалентно return F(basic_string_view(s), pos);
Каждая функция-член формы
constexpr return-type F(const charT* s, size_type pos, size_type n);
эквивалентно return F(basic_string_view(s, n), pos);
Каждая функция-член формы
constexpr return-type F(charT c, size_type pos);
эквивалентно return F(basic_string_view(&c, 1), pos);
constexpr size_type find(basic_string_view str, size_type pos = 0) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
constexpr size_type rfind(basic_string_view str, size_type pos = npos) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
constexpr size_type find_first_of(basic_string_view str, size_type pos = 0) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
constexpr size_type find_last_of(basic_string_view str, size_type pos = npos) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
constexpr size_type find_first_not_of(basic_string_view str, size_type pos = 0) const noexcept;
Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.
constexpr size_type find_last_not_of(basic_string_view str, size_type pos = npos) const noexcept;
Позвольте S быть basic_string_view<charT, traits>, и sv быть экземпляром S. Реализации должны обеспечить достаточные дополнительные перегрузки , отмеченные constexpr и noexcept таким образом , чтобы объект t с неявным преобразованием , чтобы S можно сравнить в соответствии с таблицей 67.
Выражение | Эквивалентно |
t == sv | S(t) == sv |
sv == t | sv == S(t) |
t != sv | S(t) != sv |
sv != t | sv != S(t) |
t < sv | S(t) < sv |
sv < t | sv < S(t) |
t > sv | S(t) > sv |
sv > t | sv > S(t) |
t <= sv | S(t) <= sv |
sv <= t | sv <= S(t) |
t >= sv | S(t) >= sv |
sv >= t | sv >= S(t) |
[ Example: Пример соответствующей реализации для operator== :
template<class T> using __identity = decay_t<T>; template<class charT, class traits> constexpr bool operator==(basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept { return lhs.compare(rhs) == 0; } template<class charT, class traits> constexpr bool operator==(basic_string_view<charT, traits> lhs, __identity<basic_string_view<charT, traits>> rhs) noexcept { return lhs.compare(rhs) == 0; } template<class charT, class traits> constexpr bool operator==(__identity<basic_string_view<charT, traits>> lhs, basic_string_view<charT, traits> rhs) noexcept { return lhs.compare(rhs) == 0; }
— end example ]
template<class charT, class traits>
constexpr bool operator==(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
template<class charT, class traits>
constexpr bool operator!=(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
template<class charT, class traits>
constexpr bool operator< (basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
template<class charT, class traits>
constexpr bool operator> (basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
template<class charT, class traits>
constexpr bool operator<=(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
template<class charT, class traits>
constexpr bool operator>=(basic_string_view<charT, traits> lhs,
basic_string_view<charT, traits> rhs) noexcept;
template<class charT, class traits>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& os,
basic_string_view<charT, traits> str);
Effects: Ведет себя как formatted output function оф os. Формирует последовательность символов seq, изначально состоящую из элементов, определенных диапазоном [str.begin(), str.end()). Определяет заполнение, seq как описано в [ostream.formatted.reqmts]. Затем вставляет seq как бы по вызову os.rdbuf()->sputn(seq, n), где n больше из os.width() и str.size(); потом звонит os.width(0).
template<> struct hash<string_view>;
template<> struct hash<u16string_view>;
template<> struct hash<u32string_view>;
template<> struct hash<wstring_view>;
Специализация включена ([unord.hash]). [ Note: Хеш-значение объекта строкового представления равно хэш-значению соответствующего строкового объекта ([basic.string.hash]). ] — end note
constexpr string_view operator""sv(const char* 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;
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); }
namespace std { using wint_t = see below; using wctrans_t = see below; using wctype_t = see below; int iswalnum(wint_t wc); int iswalpha(wint_t wc); int iswblank(wint_t wc); int iswcntrl(wint_t wc); int iswdigit(wint_t wc); int iswgraph(wint_t wc); int iswlower(wint_t wc); int iswprint(wint_t wc); int iswpunct(wint_t wc); int iswspace(wint_t wc); int iswupper(wint_t wc); int iswxdigit(wint_t wc); int iswctype(wint_t wc, wctype_t desc); wctype_t wctype(const char* property); wint_t towlower(wint_t wc); wint_t towupper(wint_t wc); wint_t towctrans(wint_t wc, wctrans_t desc); wctrans_t wctrans(const char* property); } #define WEOF see below
namespace std { using size_t = see [support.types.layout]; void* memcpy(void* s1, const void* s2, size_t n); void* memmove(void* s1, const void* s2, size_t n); char* strcpy(char* s1, const char* s2); char* strncpy(char* s1, const char* s2, size_t n); char* strcat(char* s1, const char* s2); char* strncat(char* s1, const char* s2, size_t n); int memcmp(const void* s1, const void* s2, size_t n); int strcmp(const char* s1, const char* s2); int strcoll(const char* s1, const char* s2); int strncmp(const char* s1, const char* s2, size_t n); size_t strxfrm(char* s1, const char* s2, size_t n); const void* memchr(const void* s, int c, size_t n); // see [library.c] void* memchr(void* s, int c, size_t n) // see [library.c] const char* strchr(const char* s, int c) // see [library.c] char* strchr(char* s, int c) // see [library.c] size_t strcspn(const char* s1, const char* s2); const char* strpbrk(const char* s1, const char* s2) // see [library.c] char* strpbrk(char* s1, const char* s2) // see [library.c] const char* strrchr(const char* s, int c) // see [library.c] char* strrchr(char* s, int c) // see [library.c] size_t strspn(const char* s1, const char* s2); const char* strstr(const char* s1, const char* s2) // see [library.c] char* strstr(char* s1, const char* s2) // see [library.c] char* strtok(char* s1, const char* s2); void* memset(void* s, int c, size_t n); char* strerror(int errnum); size_t strlen(const char* s); } #define NULL see [support.types.nullptr]
Содержание и значение заголовка <cstring> такие же , как заголовок стандартной библиотеки C <string.h>.
[ Note: Функция strchr, strpbrk, strrchr, strstr, и memchr, имеют разные подписи в настоящем стандарте, но они имеют такое же поведение , как и в C standard library. ] — end note
См. Также: ISO C 7.24.
namespace std { using size_t = see [support.types.layout]; using mbstate_t = see below; using wint_t = see below; struct tm; int fwprintf(FILE* stream, const wchar_t* format, ...); int fwscanf(FILE* stream, const wchar_t* format, ...); int swprintf(wchar_t* s, size_t n, const wchar_t* format, ...); int swscanf(const wchar_t* s, const wchar_t* format, ...); int vfwprintf(FILE* stream, const wchar_t* format, va_list arg); int vfwscanf(FILE* stream, const wchar_t* format, va_list arg); int vswprintf(wchar_t* s, size_t n, const wchar_t* format, va_list arg); int vswscanf(const wchar_t* s, const wchar_t* format, va_list arg); int vwprintf(const wchar_t* format, va_list arg); int vwscanf(const wchar_t* format, va_list arg); int wprintf(const wchar_t* format, ...); int wscanf(const wchar_t* format, ...); wint_t fgetwc(FILE* stream); wchar_t* fgetws(wchar_t* s, int n, FILE* stream); wint_t fputwc(wchar_t c, FILE* stream); int fputws(const wchar_t* s, FILE* stream); int fwide(FILE* stream, int mode); wint_t getwc(FILE* stream); wint_t getwchar(); wint_t putwc(wchar_t c, FILE* stream); wint_t putwchar(wchar_t c); wint_t ungetwc(wint_t c, FILE* stream); double wcstod(const wchar_t* nptr, wchar_t** endptr); float wcstof(const wchar_t* nptr, wchar_t** endptr); long double wcstold(const wchar_t* nptr, wchar_t** endptr); long int wcstol(const wchar_t* nptr, wchar_t** endptr, int base); long long int wcstoll(const wchar_t* nptr, wchar_t** endptr, int base); unsigned long int wcstoul(const wchar_t* nptr, wchar_t** endptr, int base); unsigned long long int wcstoull(const wchar_t* nptr, wchar_t** endptr, int base); wchar_t* wcscpy(wchar_t* s1, const wchar_t* s2); wchar_t* wcsncpy(wchar_t* s1, const wchar_t* s2, size_t n); wchar_t* wmemcpy(wchar_t* s1, const wchar_t* s2, size_t n); wchar_t* wmemmove(wchar_t* s1, const wchar_t* s2, size_t n); wchar_t* wcscat(wchar_t* s1, const wchar_t* s2); wchar_t* wcsncat(wchar_t* s1, const wchar_t* s2, size_t n); int wcscmp(const wchar_t* s1, const wchar_t* s2); int wcscoll(const wchar_t* s1, const wchar_t* s2); int wcsncmp(const wchar_t* s1, const wchar_t* s2, size_t n); size_t wcsxfrm(wchar_t* s1, const wchar_t* s2, size_t n); int wmemcmp(const wchar_t* s1, const wchar_t* s2, size_t n); const wchar_t* wcschr(const wchar_t* s, wchar_t c) // see [library.c] wchar_t* wcschr(wchar_t* s, wchar_t c) // see [library.c] size_t wcscspn(const wchar_t* s1, const wchar_t* s2); const wchar_t* wcspbrk(const wchar_t* s1, const wchar_t* s2) // see [library.c] wchar_t* wcspbrk(wchar_t* s1, const wchar_t* s2) // see [library.c] const wchar_t* wcsrchr(const wchar_t* s, wchar_t c) // see [library.c] wchar_t* wcsrchr(wchar_t* s, wchar_t c) // see [library.c] size_t wcsspn(const wchar_t* s1, const wchar_t* s2); const wchar_t* wcsstr(const wchar_t* s1, const wchar_t* s2) // see [library.c] wchar_t* wcsstr(wchar_t* s1, const wchar_t* s2) // see [library.c] wchar_t* wcstok(wchar_t* s1, const wchar_t* s2, wchar_t** ptr); const wchar_t* wmemchr(const wchar_t* s, wchar_t c, size_t n) // see [library.c] wchar_t* wmemchr(wchar_t* s, wchar_t c, size_t n) // see [library.c] size_t wcslen(const wchar_t* s); wchar_t* wmemset(wchar_t* s, wchar_t c, size_t n); size_t wcsftime(wchar_t* s, size_t maxsize, const wchar_t* format, const struct tm* timeptr); wint_t btowc(int c); int wctob(wint_t c); // [c.mb.wcs], multibyte / wide string and character conversion functions int mbsinit(const mbstate_t* ps); size_t mbrlen(const char* s, size_t n, mbstate_t* ps); size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t* ps); size_t wcrtomb(char* s, wchar_t wc, mbstate_t* ps); size_t mbsrtowcs(wchar_t* dst, const char** src, size_t len, mbstate_t* ps); size_t wcsrtombs(char* dst, const wchar_t** src, size_t len, mbstate_t* ps); } #define NULL see [support.types.nullptr] #define WCHAR_MAX see below #define WCHAR_MIN see below #define WEOF see below
Содержание и значение заголовка <cwchar> такие же, как и у заголовка стандартной библиотеки C <wchar.h>, за исключением того, что он не объявляет тип wchar_t.
[ Note: Функция wcschr, wcspbrk, wcsrchr, wcsstr, и wmemchr имеют разные подписи в настоящем стандарте, но они имеют такое же поведение , как и в C standard library. ] — end note
См. Также: ISO C 7.29
namespace std { using mbstate_t = see below; using size_t = see [support.types.layout]; 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); }
int mbsinit(const mbstate_t* ps);
int mblen(const char* s, size_t n);
size_t mbstowcs(wchar_t* pwcs, const char* s, size_t n);
size_t wcstombs(char* s, const wchar_t* pwcs, size_t n);
См. Также: ISO C 7.22.7.1, 7.22.8, 7.29.6.2.1
int mbtowc(wchar_t* pwc, const char* s, size_t n);
int wctomb(char* s, wchar_t wchar);
Remarks: Вызов этих функций может вызвать гонку данных ([res.on.data.races]) с другими вызовами той же функции.
См. Также: ISO C 7.22.7
size_t mbrlen(const char* s, size_t n, mbstate_t* ps);
size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t* ps);
size_t wcrtomb(char* s, wchar_t wc, mbstate_t* ps);
size_t mbsrtowcs(wchar_t* dst, const char** src, size_t len, mbstate_t* ps);
size_t wcsrtombs(char* dst, const wchar_t** src, size_t len, mbstate_t* ps);
Remarks: Вызов этих функций с mbstate_t* аргументом, который является значением нулевого указателя, может вызвать гонку данных ([res.on.data.races]) с другими вызовами той же функции с mbstate_t* аргументом, который является значением нулевого указателя.
См. Также: ISO C 7.29.6.3.