24 Strings library [strings]

24.3 String classes [string.classes]

Заголовка <string> определяет basic_­string шаблон класса для манипулирования переменной длины последовательности углеродно как объекты и четыре typedef-names, string, u16string, u32string, и wstring, что имя специализации basic_­string<char>, basic_­string<char16_­t>, basic_­string<char32_­t>, и basic_­string<​wchar_­t>, соответственно.

24.3.1 Header <string> synopsis [string.syn]

#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);
  }
  }
}

24.3.2 Class template basic_­string [basic.string]

Шаблон класса basic_­string описывает объекты, которые могут хранить последовательность, состоящую из переменного числа произвольных char-подобных объектов, с первым элементом последовательности в нулевой позиции. Такая последовательность также называется «строкой», если тип char-подобных объектов, которые она содержит, ясен из контекста. В остальной части этого раздела тип char-подобных объектов, содержащихся в basic_­string объекте, обозначается с помощью charT.

Функции-члены basic_­string используют объект Allocator класса, переданный в качестве параметра шаблона, для выделения и освобождения памяти для содержащихся в нем объектов типа char.225

А basic_­string - это contiguous container.

Во всех случаях size() <= capacity().

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

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

24.3.2.1 basic_­string general requirements [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().

24.3.2.2 basic_­string constructors and assignment operators [string.cons]

explicit basic_string(const Allocator& a) noexcept;

Effects: Создает объект класса basic_­string. Постусловия этой функции указаны в таблице 55.

Таблица 55 - basic_­string(const Allocator&) эффекты
ЭлементЦенить
data() ненулевой указатель, который можно копировать и к нему можно добавить 0
size() 0
capacity() неуказанное значение

basic_string(const basic_string& str); basic_string(basic_string&& str) noexcept;

Effects: Создает объект класса, basic_­string как указано в Табл 56. Во второй форме str остается в допустимом состоянии с неопределенным значением.

Таблица 56 - basic_­string(const basic_­string&) эффекты
ЭлементЦенить
data() указывает на первый элемент выделенной копии массива, на первый элемент которого указывает str.data()
size() str.size()
capacity() значение, по крайней мере, такое большое, как size()

basic_string(const basic_string& str, size_type pos, const Allocator& a = Allocator());

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

Effects: Создает объект класса basic_­string и определяет эффективную длину rlen начального строкового значения str.size() - pos, как указано в Табл 57.

basic_string(const basic_string& str, size_type pos, size_type n, const Allocator& a = Allocator());

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

Effects: Создает объект класса basic_­string и определяет эффективную длину rlen начального строкового значения как меньшее из n и str.size() - pos, как указано в таблице 57.

Таблица 57 - и эффекты basic_­string(const basic_­string&, size_­type, const Allocator&)
basic_­string(const basic_­string&, size_­type, size_­type, const Allocator&)
ЭлементЦенить
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());

Effects: То же, что и basic_­string(sv.data(), sv.size(), a).

basic_string(const charT* s, size_type n, const Allocator& a = Allocator());

Requires: s указывает на массив, состоящий как минимум из n элементов charT.

Effects: Создает объект класса basic_­string и определяет его начальное строковое значение из массива charT длины n , первый элемент которого обозначен s, как указано в таблице 58.

Таблица 58 - basic_­string(const charT*, size_­type, const Allocator&) эффекты
ЭлементЦенить
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.

Таблица 59 - basic_­string(const charT*, const Allocator&) эффекты
ЭлементЦенить
data() указывает на первый элемент выделенной копии массива, на первый элемент которого указывает s
size() traits​::​length(s)
capacity() значение, по крайней мере, такое большое, как size()

basic_string(size_type n, charT c, const Allocator& a = Allocator());

Requires: n < npos.

Effects: Создает объект класса basic_­string и определяет его начальное строковое значение, повторяя объект типа char c для всех n элементов, как указано в таблице 60.

Таблица 60 - basic_­string(size_­t, charT, const Allocator&) эффекты
ЭлементЦенить
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());

Effects: То же, что и basic_­string(il.begin(), il.end(), a).

basic_string(const basic_string& str, const Allocator& alloc); basic_string(basic_string&& str, const Allocator& alloc);

Effects: Создает объект класса, basic_­string как указано в Табл 61. Сохраненный распределитель построен из alloc. Во второй форме str остается в допустимом состоянии с неопределенным значением.

Таблица 61 - и эффекты basic_­string(const basic_­string&, const Allocator&)
basic_­string(basic_­string&&, const Allocator&)
ЭлементЦенить
data() указывает на первый элемент выделенной копии массива, на первый элемент которого указывает исходное значение str.data().
size() первоначальная стоимость str.size()
capacity() значение, по крайней мере, такое большое, как size()
get_­allocator() alloc

Throws: Вторая форма ничего не бросает, если alloc == str.get_­allocator().

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

Effects: Если *this и str являются разными объектами, изменяется, *this как показано в Табл 62.

Если *this и str являются одним и тем же объектом, член не имеет никакого эффекта.

Returns: *this.

Таблица 62 - operator=(const basic_­string&) эффекты
ЭлементЦенить
data() указывает на первый элемент выделенной копии массива, на первый элемент которого указывает str.data()
size() str.size()
capacity() значение, по крайней мере, такое большое, как size()

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, за исключением того, что итераторы, указатели и ссылки могут быть недействительными.

Returns: *this.

basic_string& operator=(basic_string_view<charT, traits> sv);

Effects: Эквивалентен: return assign(sv);

basic_string& operator=(const charT* s);

Returns: *this = basic_­string(s).

Remarks: Использует traits​::​length().

basic_string& operator=(charT c);

Returns: *this = basic_­string(1, c).

basic_string& operator=(initializer_list<charT> il);

Effects: Как будто по: *this = basic_­string(il);

Returns: *this.

24.3.2.3 basic_­string iterator support [string.iterators]

iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept;

Returns: Итератор, относящийся к первому символу в строке.

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

Returns: Итератор, являющийся последним значением.

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

Returns: Итератор, семантически эквивалентный reverse_­iterator(end()).

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

Returns: Итератор, семантически эквивалентный reverse_­iterator(begin()).

24.3.2.4 basic_­string capacity [string.capacity]

size_type size() const noexcept;

Returns: Подсчет количества символьных объектов, находящихся в данный момент в строке.

Complexity: Постоянное время.

size_type length() const noexcept;

Returns: size().

size_type max_size() const noexcept;

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

Complexity: Постоянное время.

void resize(size_type n, charT c);

Throws: length_­error если n > max_­size().

Effects: Изменяет длину строки, обозначенной *this следующим образом:

  • Если n <= size()функция заменяет строку, обозначенную знаком, *this строкой длины n , элементы которой являются копией начальных элементов исходной строки, обозначенной *this.

  • Если n > size(), функция заменяет строку, обозначенную *this с помощью, строкой длины n , первые size() элементы которой являются копией исходной строки, обозначенной с помощью *this, а остальные элементы которой инициализируются c.

void resize(size_type n);

Effects: Как будто мимо resize(n, charT()).

size_type capacity() const noexcept;

Returns: Размер выделенного хранилища в строке.

void reserve(size_type res_arg=0);

Функция-член reserve() - это директива, информирующая basic_­string объект о запланированном изменении размера, чтобы он мог соответствующим образом управлять распределением хранилища.

Effects: После тогоreserve(), capacity() больше или равен аргумент reserve. [ Note: Вызов reserve() с res_­arg аргументом, меньшим чем capacity() , по сути, является необязательным запросом на сжатие. Обращение с помощью res_­arg <= size() по сути является необязательным запросом на усадку по размеру. ]end note

Throws: length_­error если res_­arg > max_­size().227

void shrink_to_fit();

Effects: shrink_­to_­fit является необязательным запросом для сокращения capacity() до size(). [ Note: Запрос не является обязывающим, чтобы дать свободу для оптимизации, зависящей от реализации. ] Он не увеличивается , но может уменьшаться , вызывая перераспределение. end note capacity() capacity()

Complexity: Линейный по размеру последовательности.

Remarks: Перераспределение делает недействительными все ссылки, указатели и итераторы, относящиеся к элементам в последовательности, а также к итератору, прошедшему конец. Если перераспределения не происходит, они остаются в силе.

void clear() noexcept;

Effects: Ведет себя так, как будто функция вызывает:

erase(begin(), end());

bool empty() const noexcept;

Returns: size() == 0.

reserve() использования, allocator_­traits<Allocator>​::​allocate() которые могут вызвать соответствующее исключение.

24.3.2.5 basic_­string element access [string.access]

const_reference operator[](size_type pos) const; reference operator[](size_type pos);

Requires: pos <= size().

Returns: *(begin() + pos) если pos < size(). В противном случае возвращает ссылку на объект типа charT со значением charT(), где изменение объекта на любое значение, кроме charT() приводит к неопределенному поведению.

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

Complexity: Постоянное время.

const_reference at(size_type pos) const; reference at(size_type pos);

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

Returns: operator[](pos).

const charT& front() const; charT& front();

Requires: !empty().

Effects: Эквивалентен: return operator[](0);

const charT& back() const; charT& back();

Requires: !empty().

Effects: Эквивалентен: return operator[](size() - 1);

24.3.2.6 basic_­string modifiers [string.modifiers]

24.3.2.6.1 basic_­string​::​operator+= [string.op+=]

basic_string& operator+=(const basic_string& str);

Effects: Звонки append(str).

Returns: *this.

basic_string& operator+=(basic_string_view<charT, traits> sv);

Effects: Звонки append(sv).

Returns: *this.

basic_string& operator+=(const charT* s);

Effects: Звонки append(s).

Returns: *this.

basic_string& operator+=(charT c);

Effects: Звонки push_­back(c);

Returns: *this.

basic_string& operator+=(initializer_list<charT> il);

Effects: Звонки append(il).

Returns: *this.

24.3.2.6.2 basic_­string​::​append [string.append]

basic_string& append(const basic_string& str);

Effects: Звонки append(str.data(), str.size()).

Returns: *this.

basic_string& append(const basic_string& str, size_type pos, size_type n = npos);

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

Effects: Определяет эффективную длину rlen добавляемой строки как меньшее из вызовов n и str.size() - pos и append(str.data() + pos, rlen).

Returns: *this.

basic_string& append(basic_string_view<charT, traits> sv);

Effects: Эквивалентен: return append(sv.data(), sv.size());

template<class T> basic_string& append(const T& t, size_type pos, size_type n = npos);

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

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.

Returns: *this.

basic_string& append(const charT* s, size_type n);

Requires: s указывает на массив, состоящий как минимум из n элементов charT.

Throws: length_­error если size() + n > max_­size().

Effects: Функция заменяет строку, которой управляет, *this строкой длины size() + n , первые size() элементы которой являются копией исходной строки, которой управляет, *this а остальные элементы - копией начальных n элементов s.

Returns: *this.

basic_string& append(const charT* s);

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Effects: Звонки append(s, traits​::​length(s)).

Returns: *this.

basic_string& append(size_type n, charT c);

Effects: Эквивалентно append(basic_­string(n, c)).

Returns: *this.

template<class InputIterator> basic_string& append(InputIterator first, InputIterator last);

Requires: [first, last) допустимый диапазон.

Effects: Эквивалентно append(basic_­string(first, last, get_­allocator())).

Returns: *this.

basic_string& append(initializer_list<charT> il);

Effects: Звонки append(il.begin(), il.size()).

Returns: *this.

void push_back(charT c);

Effects: Эквивалентно append(static_­cast<size_­type>(1), c).

24.3.2.6.3 basic_­string​::​assign [string.assign]

basic_string& assign(const basic_string& str);

Effects: Эквивалентно *this = str.

Returns: *this.

basic_string& assign(basic_string&& str) noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value || allocator_traits<Allocator>::is_always_equal::value);

Effects: Эквивалентно *this = std​::​move(str).

Returns: *this.

basic_string& assign(const basic_string& str, size_type pos, size_type n = npos);

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

Effects: Определяет эффективную длину rlen строки, которая назначается как меньшее из вызовов n и str.size() - pos и assign(str.data() + pos, rlen).

Returns: *this.

basic_string& assign(basic_string_view<charT, traits> sv);

Effects: Эквивалентен: return assign(sv.data(), sv.size());

template<class T> basic_string& assign(const T& t, size_type pos, size_type n = npos);

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

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.

Returns: *this.

basic_string& assign(const charT* s, size_type n);

Requires: s указывает на массив, состоящий как минимум из n элементов charT.

Throws: length_­error если n > max_­size().

Effects: Заменяет строку, управляемую *this с помощью, строкой длины n , элементы которой являются копией тех, на которые указывает s.

Returns: *this.

basic_string& assign(const charT* s);

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Effects: Звонки assign(s, traits​::​length(s)).

Returns: *this.

basic_string& assign(initializer_list<charT> il);

Effects: Звонки assign(il.begin(), il.size()).

*this.

basic_string& assign(size_type n, charT c);

Effects: Эквивалентно assign(basic_­string(n, c)).

Returns: *this.

template<class InputIterator> basic_string& assign(InputIterator first, InputIterator last);

Effects: Эквивалентно assign(basic_­string(first, last, get_­allocator())).

Returns: *this.

24.3.2.6.4 basic_­string​::​insert [string.insert]

basic_string& insert(size_type pos, const basic_string& str);

Effects: Эквивалентен: return insert(pos, str.data(), str.size());

basic_string& insert(size_type pos1, const basic_string& str, size_type pos2, size_type n = npos);

Throws: out_­of_­range если pos1 > size() или pos2 > str.size().

Effects: Определяет эффективную длину rlen строки для вставки в качестве меньшего из вызовов n и str.size() - pos2 и insert(pos1, str.data() + pos2, rlen).

Returns: *this.

basic_string& insert(size_type pos, basic_string_view<charT, traits> sv);

Effects: Эквивалентен: return insert(pos, sv.data(), sv.size());

template<class T> basic_string& insert(size_type pos1, const T& t, size_type pos2, size_type n = npos);

Throws: out_­of_­range если pos1 > size() или pos2 > sv.size().

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.

Returns: *this.

basic_string& insert(size_type pos, const charT* s, size_type n);

Requires: s указывает на массив, состоящий как минимум из n элементов charT.

Throws: out_­of_­range если pos > size() или length_­error если size() + n > max_­size().

Effects: Заменяет строку, управляемую *this строкой длины size() + n , первые pos элементы которой являются копией начальных элементов исходной строки, которой управляет, *this и чьи следующие n элементы являются копией элементов в, s а остальные элементы являются копией остальных элементов исходная строка, управляемая *this.

Returns: *this.

basic_string& insert(size_type pos, const charT* s);

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Effects: Эквивалентен: return insert(pos, s, traits​::​length(s));

basic_string& insert(size_type pos, size_type n, charT c);

Effects: Эквивалентно insert(pos, basic_­string(n, c)).

Returns: *this.

iterator insert(const_iterator p, charT c);

Requires: p является допустимым итератором на *this.

Effects: Вставляет копию c перед символом, на который ссылается p.

Returns: Итератор, который ссылается на копию вставленного символа.

iterator insert(const_iterator p, size_type n, charT c);

Requires: p является допустимым итератором на *this.

Effects: Вставляет n копии c перед символом, на который ссылается p.

Returns: Итератор, который ссылается на копию первого вставленного символа, или p если n == 0.

template<class InputIterator> iterator insert(const_iterator p, InputIterator first, InputIterator last);

Requires: p является допустимым итератором на *this. [first, last) допустимый диапазон.

Effects: Эквивалентно insert(p - begin(), basic_­string(first, last, get_­allocator())).

Returns: Итератор, который ссылается на копию первого вставленного символа, или p если first == last.

iterator insert(const_iterator p, initializer_list<charT> il);

Effects: Как будто мимо insert(p, il.begin(), il.end()).

Returns: Итератор, который ссылается на копию первого вставленного символа или p если i1 он пуст.

24.3.2.6.5 basic_­string​::​erase [string.erase]

basic_string& erase(size_type pos = 0, size_type n = npos);

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

Effects: Определяет эффективную длину xlen удаляемой строки как меньшее из значений n и size() - pos.

Затем функция заменяет строку, управляемую *this с помощью строки длины size() - xlen , первые pos элементы которой являются копией начальных элементов исходной строки, которой управляет *this, а остальные элементы которой являются копией элементов исходной строки, управляемой *this начиная с позиции pos + xlen.

Returns: *this.

iterator erase(const_iterator p);

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

Effects: Удаляет символ, на который ссылается p.

Returns: Итератор, который указывает на элемент, следующий непосредственно за p стираемым элементом. Если такого элемента не существует, end() возвращается.

iterator erase(const_iterator first, const_iterator last);

Requires: first и last являются действительными итераторами *this, определяющими диапазон [first, last).

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

Effects: Удаляет символы в диапазоне [first, last).

Returns: Итератор, который указывает на элемент, на который указывает до last удаления других элементов. Если такого элемента не существует, end() возвращается.

void pop_back();

Requires: !empty().

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

Effects: Эквивалентно erase(size() - 1, 1).

24.3.2.6.6 basic_­string​::​replace [string.replace]

basic_string& replace(size_type pos1, size_type n1, const basic_string& str);

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

basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2 = npos);

Throws: out_­of_­range если pos1 > size() или pos2 > str.size().

Effects: Определяет эффективную длину rlen вставляемой строки как меньшее из вызовов n2 и str.size() - pos2 и replace(pos1, n1, str.data() + pos2, rlen).

Returns: *this.

basic_string& replace(size_type pos1, size_type n1, basic_string_view<charT, traits> sv);

Effects: Эквивалентен: return replace(pos1, n1, sv.data(), sv.size());

template<class T> basic_string& replace(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos);

Throws: out_­of_­range если pos1 > size() или pos2 > sv.size().

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.

Returns: *this.

basic_string& replace(size_type pos1, size_type n1, const charT* s, size_type n2);

Requires: s указывает на массив, состоящий как минимум из n2 элементов charT.

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.

Returns: *this.

basic_string& replace(size_type pos, size_type n, const charT* s);

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Effects: Эквивалентен: return replace(pos, n, s, traits​::​length(s));

basic_string& replace(size_type pos1, size_type n1, size_type n2, charT c);

Effects: Эквивалентно replace(pos1, n1, basic_­string(n2, c)).

Returns: *this.

basic_string& replace(const_iterator i1, const_iterator i2, const basic_string& str);

Requires: [begin(), i1) и [i1, i2) допустимые диапазоны.

Effects: Звонки replace(i1 - begin(), i2 - i1, str).

Returns: *this.

basic_string& replace(const_iterator i1, const_iterator i2, basic_string_view<charT, traits> sv);

Requires: [begin(), i1) и [i1, i2) допустимые диапазоны.

Effects: Звонки replace(i1 - begin(), i2 - i1, sv).

Returns: *this.

basic_string& replace(const_iterator i1, const_iterator i2, const charT* s, size_type n);

Requires: [begin(), i1) и [i1, i2) являются допустимыми диапазонами и s указывают на массив, состоящий как минимум из n элементов charT.

Effects: Звонки replace(i1 - begin(), i2 - i1, s, n).

Returns: *this.

basic_string& replace(const_iterator i1, const_iterator i2, const charT* s);

Requires: [begin(), i1) и [i1, i2) являются допустимыми диапазонами и s указывают на массив, состоящий как минимум из traits​::​​length(s) + 1 элементов charT.

Effects: Звонки replace(i1 - begin(), i2 - i1, s, traits​::​length(s)).

Returns: *this.

basic_string& replace(const_iterator i1, const_iterator i2, size_type n, charT c);

Requires: [begin(), i1) и [i1, i2) допустимые диапазоны.

Effects: Звонки replace(i1 - begin(), i2 - i1, basic_­string(n, c)).

Returns: *this.

template<class InputIterator> basic_string& replace(const_iterator i1, const_iterator i2, InputIterator j1, InputIterator j2);

Requires: [begin(), i1), [i1, i2) и [j1, j2) допустимые диапазоны.

Effects: Звонки replace(i1 - begin(), i2 - i1, basic_­string(j1, j2, get_­allocator())).

Returns: *this.

basic_string& replace(const_iterator i1, const_iterator i2, initializer_list<charT> il);

Requires: [begin(), i1) и [i1, i2) допустимые диапазоны.

Effects: Звонки replace(i1 - begin(), i2 - i1, il.begin(), il.size()).

Returns: *this.

24.3.2.6.7 basic_­string​::​copy [string.copy]

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). [ Note: Это не заканчивается s нулевым объектом. ] end note

Returns: rlen.

24.3.2.6.8 basic_­string​::​swap [string.swap]

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.

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

Complexity: Постоянное время.

24.3.2.7 basic_­string string operations [string.ops]

24.3.2.7.1 basic_­string accessors [string.accessors]

const charT* c_str() const noexcept; const charT* data() const noexcept;

Returns: Указатель p такой, что p + i == &operator[](i) для каждого i в [0, size()].

Complexity: Постоянное время.

Requires: Программа не должна изменять никаких значений, хранящихся в массиве символов.

charT* data() noexcept;

Returns: Указатель p такой, что p + i == &operator[](i) для каждого i в [0, size()].

Complexity: Постоянное время.

Requires: Программа не должна изменять значение, хранящееся в p + size().

operator basic_string_view<charT, traits>() const noexcept;

Effects: Эквивалентен: return basic_­string_­view<charT, traits>(data(), size());

allocator_type get_allocator() const noexcept;

Returns: Копия Allocator объекта, используемого для создания строки, или, если этот распределитель был заменен, копия самой последней замены.

24.3.2.7.2 basic_­string​::​find [string.find]

size_type find(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept;

Effects: Определяет xpos, если возможно, самое низкое положение , при котором выполняются оба следующих условия:

  • pos <= xpos и xpos + sv.size() <= size();

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

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

size_type find(const basic_string& str, size_type pos = 0) const noexcept;

Effects: Эквивалентен: return find(basic_­string_­view<charT, traits>(str), pos);

size_type find(const charT* s, size_type pos, size_type n) const;

Returns: find(basic_­string_­view<charT, traits>(s, n), pos).

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

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Returns: find(basic_­string_­view<charT, traits>(s), pos).

size_type find(charT c, size_type pos = 0) const;

Returns: find(basic_­string(1, c), pos).

24.3.2.7.3 basic_­string​::​rfind [string.rfind]

size_type rfind(basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept;

Effects: Определяет xpos, если возможно, наивысшее положение , при котором выполняются оба следующих условия:

  • xpos <= pos и xpos + sv.size() <= size();

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

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

size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;

Effects: Эквивалентен: return rfind(basic_­string_­view<charT, traits>(str), pos);

size_type rfind(const charT* s, size_type pos, size_type n) const;

Returns: rfind(basic_­string_­view<charT, traits>(s, n), pos).

size_type rfind(const charT* s, size_type pos = npos) const;

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Returns: rfind(basic_­string_­view<charT, traits>(s), pos).

size_type rfind(charT c, size_type pos = npos) const;

Returns: rfind(basic_­string(1, c), pos).

24.3.2.7.4 basic_­string​::​find_­first_­of [string.find.first.of]

size_type find_first_of(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept;

Effects: Определяет xpos, если возможно, самое низкое положение , при котором выполняются оба следующих условия:

  • pos <= xpos и xpos < size();

  • traits​::​eq(at(xpos), sv.at(I)) для некоторого элемента I данных, на который ссылается sv.

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

size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;

Effects: Эквивалентен: return find_­first_­of(basic_­string_­view<charT, traits>(str), pos);

size_type find_first_of(const charT* s, size_type pos, size_type n) const;

Returns: find_­first_­of(basic_­string_­view<charT, traits>(s, n), pos).

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

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Returns: find_­first_­of(basic_­string_­view<charT, traits>(s), pos).

size_type find_first_of(charT c, size_type pos = 0) const;

Returns: find_­first_­of(basic_­string(1, c), pos).

24.3.2.7.5 basic_­string​::​find_­last_­of [string.find.last.of]

size_type find_last_of(basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept;

Effects: Определяет xpos, если возможно, наивысшее положение , при котором выполняются оба следующих условия:

  • xpos <= pos и xpos < size();

  • traits​::​eq(at(xpos), sv.at(I)) для некоторого элемента I данных, на который ссылается sv.

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

size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept;

Effects: Эквивалентен: return find_­last_­of(basic_­string_­view<charT, traits>(str), pos);

size_type find_last_of(const charT* s, size_type pos, size_type n) const;

Returns: find_­last_­of(basic_­string_­view<charT, traits>(s, n), pos).

size_type find_last_of(const charT* s, size_type pos = npos) const;

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Returns: find_­last_­of(basic_­string_­view<charT, traits>(s), pos).

size_type find_last_of(charT c, size_type pos = npos) const;

Returns: find_­last_­of(basic_­string(1, c), pos).

24.3.2.7.6 basic_­string​::​find_­first_­not_­of [string.find.first.not.of]

size_type find_first_not_of(basic_string_view<charT, traits> sv, size_type pos = 0) const noexcept;

Effects: Определяет xpos, если возможно, самое низкое положение , при котором выполняются оба следующих условия:

  • pos <= xpos и xpos < size();

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

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

size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;

Effects: Эквивалентен:

return find_first_not_of(basic_string_view<charT, traits>(str), pos);

size_type find_first_not_of(const charT* s, size_type pos, size_type n) const;

Returns: find_­first_­not_­of(basic_­string_­view<charT, traits>(s, n), pos).

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

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Returns: find_­first_­not_­of(basic_­string_­view<charT, traits>(s), pos).

size_type find_first_not_of(charT c, size_type pos = 0) const;

Returns: find_­first_­not_­of(basic_­string(1, c), pos).

24.3.2.7.7 basic_­string​::​find_­last_­not_­of [string.find.last.not.of]

size_type find_last_not_of(basic_string_view<charT, traits> sv, size_type pos = npos) const noexcept;

Effects: Определяет xpos, если возможно, наивысшее положение , при котором выполняются оба следующих условия:

  • xpos <= pos и xpos < size();

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

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

size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept;

Effects: Эквивалентен:

return find_last_not_of(basic_string_view<charT, traits>(str), pos);

size_type find_last_not_of(const charT* s, size_type pos, size_type n) const;

Returns: find_­last_­not_­of(basic_­string_­view<charT, traits>(s, n), pos).

size_type find_last_not_of(const charT* s, size_type pos = npos) const;

Requires: s указывает на массив, состоящий как минимум из traits​::​length(s) + 1 элементов charT.

Returns: find_­last_­not_­of(basic_­string_­view<charT, traits>(s), pos).

size_type find_last_not_of(charT c, size_type pos = npos) const;

Returns: find_­last_­not_­of(basic_­string(1, c), pos).

24.3.2.7.8 basic_­string​::​substr [string.substr]

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

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

Effects: Определяет эффективную длину rlen копируемой строки как меньшее из значений n и size() - pos.

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

24.3.2.7.9 basic_­string​::​compare [string.compare]

int compare(basic_string_view<charT, traits> sv) const noexcept;

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

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

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

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;

Effects: Эквивалентен: return compare(basic_­string_­view<charT, traits>(str));

int compare(size_type pos1, size_type n1, const basic_string& str) const;

Effects: Эквивалентен: return compare(pos1, n1, basic_­string_­view<charT, traits>(str));

int compare(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2 = npos) const;

Effects: Эквивалентен:

return compare(pos1, n1, basic_string_view<charT, traits>(str), pos2, n2);

int compare(const charT* s) const;

Returns: compare(basic_­string(s)).

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

Returns: basic_­string(*this, pos, n1).compare(basic_­string(s)).

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

Returns: basic_­string(*this, pos, n1).compare(basic_­string(s, n2)).

24.3.3 basic_­string non-member functions [string.nonmembers]

24.3.3.1 operator+ [string.op+]

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

Returns: basic_­string<charT, traits, Allocator>(lhs).append(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);

Returns: std​::​move(lhs.append(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);

Returns: std​::​move(rhs.insert(0, lhs)).

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

Returns: basic_­string<charT, traits, Allocator>(lhs) + rhs.

Remarks: Использует traits​::​length().

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(const charT* lhs, basic_string<charT, traits, Allocator>&& rhs);

Returns: std​::​move(rhs.insert(0, lhs)).

Remarks: Использует traits​::​length().

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(charT lhs, const basic_string<charT, traits, Allocator>& rhs);

Returns: basic_­string<charT, traits, Allocator>(1, lhs) + rhs.

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(charT lhs, basic_string<charT, traits, Allocator>&& rhs);

Returns: std​::​move(rhs.insert(0, 1, lhs)).

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs);

Returns: lhs + basic_­string<charT, traits, Allocator>(rhs).

Remarks: Использует traits​::​length().

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(basic_string<charT, traits, Allocator>&& lhs, const charT* rhs);

Returns: std​::​move(lhs.append(rhs)).

Remarks: Использует traits​::​length().

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(const basic_string<charT, traits, Allocator>& lhs, charT rhs);

Returns: lhs + basic_­string<charT, traits, Allocator>(1, rhs).

template<class charT, class traits, class Allocator> basic_string<charT, traits, Allocator> operator+(basic_string<charT, traits, Allocator>&& lhs, charT rhs);

Returns: std​::​move(lhs.append(1, rhs)).

24.3.3.2 operator== [string.operator==]

template<class charT, class traits, class Allocator> bool operator==(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;

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

template<class charT, class traits, class Allocator> bool operator==(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

Returns: rhs == lhs.

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.

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

24.3.3.3 operator!= [string.op!=]

template<class charT, class traits, class Allocator> bool operator!=(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;

Returns: !(lhs == rhs).

template<class charT, class traits, class Allocator> bool operator!=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

Returns: rhs != lhs.

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.

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

24.3.3.4 operator< [string.op<]

template<class charT, class traits, class Allocator> bool operator< (const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;

Returns: lhs.compare(rhs) < 0.

template<class charT, class traits, class Allocator> bool operator< (const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

Returns: rhs.compare(lhs) > 0.

template<class charT, class traits, class Allocator> bool operator< (const basic_string<charT, traits, Allocator>& lhs, const charT* rhs);

Returns: lhs.compare(rhs) < 0.

24.3.3.5 operator> [string.op>]

template<class charT, class traits, class Allocator> bool operator> (const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;

Returns: lhs.compare(rhs) > 0.

template<class charT, class traits, class Allocator> bool operator> (const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

Returns: rhs.compare(lhs) < 0.

template<class charT, class traits, class Allocator> bool operator> (const basic_string<charT, traits, Allocator>& lhs, const charT* rhs);

Returns: lhs.compare(rhs) > 0.

24.3.3.6 operator<= [string.op<=]

template<class charT, class traits, class Allocator> bool operator<=(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;

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

template<class charT, class traits, class Allocator> bool operator<=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

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

template<class charT, class traits, class Allocator> bool operator<=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs);

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

24.3.3.7 operator>= [string.op>=]

template<class charT, class traits, class Allocator> bool operator>=(const basic_string<charT, traits, Allocator>& lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;

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

template<class charT, class traits, class Allocator> bool operator>=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

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

template<class charT, class traits, class Allocator> bool operator>=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs);

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

24.3.3.8 swap [string.special]

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

Effects: Эквивалентен: lhs.swap(rhs);

24.3.3.9 Inserters and extractors [string.io]

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

Returns: is.

template<class charT, class traits, class Allocator> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& os, const basic_string<charT, traits, Allocator>& str);

Effects: Эквивалентен: return os << basic_­string_­view<charT, traits>(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]).

Returns: is.

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

Returns: getline(is, str, is.widen('\n')).

24.3.4 Numeric conversions [string.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);

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.

Returns: Конвертированный результат.

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.

Returns: Конвертированный результат.

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.

Returns: Конвертированный результат.

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.

Returns: Конвертированный результат.

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.

24.3.5 Hash support [basic.string.hash]

template<> struct hash<string>; template<> struct hash<u16string>; template<> struct hash<u32string>; template<> struct hash<wstring>;

Если S является одним из этих строковых типов, SV является соответствующим строковым типом представления и s является объектом типа S, то hash<S>()(s) == hash<SV>()(SV(s)).

24.3.6 Suffix for basic_­string literals [basic.string.literals]

string operator""s(const char* str, size_t len);

Returns: string{str, len}.

u16string operator""s(const char16_t* str, size_t len);

Returns: u16string{str, len}.

u32string operator""s(const char32_t* str, size_t len);

Returns: u32string{str, len}.

wstring operator""s(const wchar_t* str, size_t len);

Returns: wstring{str, len}.

[ Note: Тот же суффикс s используется для chrono​::​duration литералов, обозначающих секунды, но конфликта нет, поскольку суффиксы продолжительности применяются к числам, а суффиксы строковых литералов - к литералам массива символов. ]end note