24 Strings library [strings]

24.4 String view classes [string.view]

Шаблон класса 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

Если не указано иное, сложность basic_­string_­view функций-членов O(1) не указана.

24.4.1 Header <string_­view> synopsis [string.view.synop]

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> включены.

24.4.2 Class template basic_­string_­view [string.view.template]

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 относятся к одному типу.

24.4.2.1 Construction and assignment [string.view.cons]

constexpr basic_string_view() noexcept;

Effects: Создает пустой basic_­string_­view.

Postconditions: size_­ == 0 и data_­ == nullptr.

constexpr basic_string_view(const charT* str);

Requires: [str, str + traits​::​length(str)) допустимый диапазон.

Effects: Создает a basic_­string_­viewс постусловиями из Табл 64.

Таблица 64 - basic_­string_­view(const charT*) эффекты
ЭлементЦенить
data_­ str
size_­ traits​::​length(str)

Complexity: O(traits::length(str)).

constexpr basic_string_view(const charT* str, size_type len);

Requires: [str, str + len) допустимый диапазон.

Effects: Создает a basic_­string_­viewс постусловиями из Табл 65.

Таблица 65 - basic_­string_­view(const charT*, size_­type) эффекты
ЭлементЦенить
data_­ str
size_­ len

24.4.2.2 Iterator support [string.view.iterators]

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;

Returns: Итератор такой, что

  • если !empty(), &*begin() == data_­,

  • в противном случае - неопределенное значение, такое [begin(), end()) как допустимый диапазон.

constexpr const_iterator end() const noexcept; constexpr const_iterator cend() const noexcept;

Returns: begin() + size().

constexpr const_reverse_iterator rbegin() const noexcept; constexpr const_reverse_iterator crbegin() const noexcept;

Returns: const_­reverse_­iterator(end()).

constexpr const_reverse_iterator rend() const noexcept; constexpr const_reverse_iterator crend() const noexcept;

Returns: const_­reverse_­iterator(begin()).

24.4.2.3 Capacity [string.view.capacity]

constexpr size_type size() const noexcept;

Returns: size_­.

constexpr size_type length() const noexcept;

Returns: size_­.

constexpr size_type max_size() const noexcept;

Returns: Максимально возможное количество символьных объектов, на которые может ссылаться a basic_­string_­view.

constexpr bool empty() const noexcept;

Returns: size_­ == 0.

24.4.2.4 Element access [string.view.access]

constexpr const_reference operator[](size_type pos) const;

Requires: pos < size().

Returns: data_­[pos].

Throws: Ничего такого.

[ Note: В отличие от basic_­string​::​operator[], basic_­string_­view​::​operator[](size()) имеет неопределенное поведение вместо возврата charT(). ] end note

constexpr const_reference at(size_type pos) const;

Throws: out_­of_­range если pos >= size().

Returns: data_­[pos].

constexpr const_reference front() const;

Requires: !empty().

Returns: data_­[0].

Throws: Ничего такого.

constexpr const_reference back() const;

Requires: !empty().

Returns: data_­[size() - 1].

Throws: Ничего такого.

constexpr const_pointer data() const noexcept;

Returns: data_­.

[ Note: В отличие от basic_­string​::​data() строковых литералов и, data() может возвращать указатель на буфер, не оканчивающийся нулем. Поэтому переход data() к функции, которая принимает только a const charT* и ожидает строку с завершающим нулем, является ошибкой . ] end note

24.4.2.5 Modifiers [string.view.modifiers]

constexpr void remove_prefix(size_type n);

Requires: n <= size().

Effects: Эквивалентен: data_­ += n; size_­ -= n;

constexpr void remove_suffix(size_type n);

Requires: n <= size().

Effects: Эквивалентен: size_­ -= n;

constexpr void swap(basic_string_view& s) noexcept;

Effects: Меняет значения *this и s.

24.4.2.6 String operations [string.view.ops]

size_type copy(charT* s, size_type n, size_type pos = 0) const;

Позвольте rlen быть меньшим из n и size() - pos.

Throws: out_­of_­range если pos > size().

Requires: [s, s + rlen) допустимый диапазон.

Effects: Эквивалентно traits​::​copy(s, data() + pos, rlen).

Returns: rlen.

Complexity: O(rlen).

constexpr basic_string_view substr(size_type pos = 0, size_type n = npos) const;

Позвольте rlen быть меньшим из n и size() - pos.

Throws: out_­of_­range если pos > size().

Effects: Определяет rlenэффективную длину строки для ссылки.

Returns: basic_­string_­view(data() + pos, rlen).

constexpr int compare(basic_string_view str) const noexcept;

Позвольте rlen быть меньшим из size() и str.size().

Effects: Определяет rlenэффективную длину сравниваемых строк. Затем функция сравнивает две строки, вызывая traits​::​compare(data(), str.data(), rlen).

Complexity: O(rlen).

Returns: Ненулевой результат, если результат сравнения отличен от нуля. В противном случае возвращает значение, указанное в таблице 66.

Таблица 66 - compare() результаты
СостояниеВозвращаемое значение
size() < str.size() < 0
size() == str.size()  0
size() > str.size() > 0

constexpr int compare(size_type pos1, size_type n1, basic_string_view str) const;

Effects: Эквивалентен: return substr(pos1, n1).compare(str);

constexpr int compare(size_type pos1, size_type n1, basic_string_view str, size_type pos2, size_type n2) const;

Effects: Эквивалентен: return substr(pos1, n1).compare(str.substr(pos2, n2));

constexpr int compare(const charT* s) const;

Effects: Эквивалентен: return compare(basic_­string_­view(s));

constexpr int compare(size_type pos1, size_type n1, const charT* s) const;

Effects: Эквивалентен: return substr(pos1, n1).compare(basic_­string_­view(s));

constexpr int compare(size_type pos1, size_type n1, const charT* s, size_type n2) const;

Effects: Эквивалентен: return substr(pos1, n1).compare(basic_­string_­view(s, n2));

24.4.2.7 Searching [string.view.find]

В этом разделе описываются 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;

Позвольте xpos быть самой низкой позицией, если возможно, такой, что выполняются следующие условия:

  • pos <= xpos

  • xpos + str.size() <= size()

  • traits​::​eq(at(xpos + I), str.at(I)) для всех элементов I строки, на которую ссылается str.

Effects: Определяет xpos.

Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.

constexpr size_type rfind(basic_string_view str, size_type pos = npos) const noexcept;

Позвольте xpos быть высшей позицией, если возможно, такой, что выполняются следующие условия:

  • xpos <= pos

  • xpos + str.size() <= size()

  • traits​::​eq(at(xpos + I), str.at(I)) для всех элементов I строки, на которую ссылается str.

Effects: Определяет xpos.

Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.

constexpr size_type find_first_of(basic_string_view str, size_type pos = 0) const noexcept;

Позвольте xpos быть самой низкой позицией, если возможно, такой, что выполняются следующие условия:

  • pos <= xpos

  • xpos < size()

  • traits​::​eq(at(xpos), str.at(I)) для некоторого элемента I строки, на которую ссылается str.

Effects: Определяет xpos.

Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.

constexpr size_type find_last_of(basic_string_view str, size_type pos = npos) const noexcept;

Позвольте xpos быть высшей позицией, если возможно, такой, что выполняются следующие условия:

  • xpos <= pos

  • xpos < size()

  • traits​::​eq(at(xpos), str.at(I)) для некоторого элемента I строки, на которую ссылается str.

Effects: Определяет xpos.

Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.

constexpr size_type find_first_not_of(basic_string_view str, size_type pos = 0) const noexcept;

Позвольте xpos быть самой низкой позицией, если возможно, такой, что выполняются следующие условия:

  • pos <= xpos

  • xpos < size()

  • traits​::​eq(at(xpos), str.at(I)) для ни одного элемента I строки, на которую ссылается str.

Effects: Определяет xpos.

Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.

constexpr size_type find_last_not_of(basic_string_view str, size_type pos = npos) const noexcept;

Позвольте xpos быть высшей позицией, если возможно, такой, что выполняются следующие условия:

  • xpos <= pos

  • xpos < size()

  • traits​::​eq(at(xpos), str.at(I)) для ни одного элемента I строки, на которую ссылается str.

Effects: Определяет xpos.

Returns: xpos если функция может определить такое значение для xpos. В противном случае возвращается npos.

24.4.3 Non-member comparison functions [string.view.comparison]

Позвольте S быть basic_­string_­view<charT, traits>, и sv быть экземпляром S. Реализации должны обеспечить достаточные дополнительные перегрузки , отмеченные constexpr и noexcept таким образом , чтобы объект t с неявным преобразованием , чтобы S можно сравнить в соответствии с таблицей 67.

Таблица 67 - Дополнительные basic_­string_­view перегрузки для сравнения
ВыражениеЭквивалентно
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;

Returns: lhs.compare(rhs) == 0.

template<class charT, class traits> constexpr bool operator!=(basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept;

Returns: lhs.compare(rhs) != 0.

template<class charT, class traits> constexpr bool operator< (basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept;

Returns: lhs.compare(rhs) < 0.

template<class charT, class traits> constexpr bool operator> (basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept;

Returns: lhs.compare(rhs) > 0.

template<class charT, class traits> constexpr bool operator<=(basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept;

Returns: lhs.compare(rhs) <= 0.

template<class charT, class traits> constexpr bool operator>=(basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept;

Returns: lhs.compare(rhs) >= 0.

24.4.4 Inserters and extractors [string.view.io]

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).

Returns: os

24.4.5 Hash support [string.view.hash]

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

24.4.6 Suffix for basic_­string_­view literals [string.view.literals]

constexpr string_view operator""sv(const char* str, size_t len) noexcept;

Returns: string_­view{str, len}.

constexpr u16string_view operator""sv(const char16_t* str, size_t len) noexcept;

Returns: u16string_­view{str, len}.

constexpr u32string_view operator""sv(const char32_t* str, size_t len) noexcept;

Returns: u32string_­view{str, len}.

constexpr wstring_view operator""sv(const wchar_t* str, size_t len) noexcept;

Returns: wstring_­view{str, len}.