std::basic_string<CharT,Traits,Allocator>::insert
| (1) | ||
basic_string& insert( size_type index, size_type count, CharT ch ); | (до C++20) | |
constexpr basic_string& insert( size_type index, size_type count, CharT ch ); | (с C++20) | |
| (2) | ||
basic_string& insert( size_type index, const CharT* s ); | (до C++20) | |
constexpr basic_string& insert( size_type index, const CharT* s ); | (с C++20) | |
| (3) | ||
basic_string& insert( size_type index, const CharT* s, size_type count ); | (до C++20) | |
constexpr basic_string& insert( size_type index,
const CharT* s, size_type count );
| (с C++20) | |
| (4) | ||
basic_string& insert( size_type index, const basic_string& str ); | (до C++20) | |
constexpr basic_string& insert( size_type index, const basic_string& str ); | (с C++20) | |
| (5) | ||
basic_string& insert( size_type index, const basic_string& str,
size_type s_index, size_type count ); | (до C++14) | |
basic_string& insert( size_type index, const basic_string& str,
size_type s_index, size_type count = npos );
| (с C++14) (до C++20) | |
constexpr basic_string& insert( size_type index, const basic_string& str,
size_type s_index, size_type count = npos );
| (с C++20) | |
| (6) | ||
iterator insert( iterator pos, CharT ch ); | (до C++11) | |
iterator insert( const_iterator pos, CharT ch ); | (с C++11) (до C++20) | |
constexpr iterator insert( const_iterator pos, CharT ch ); | (с C++20) | |
| (7) | ||
void insert( iterator pos, size_type count, CharT ch ); | (до C++11) | |
iterator insert( const_iterator pos, size_type count, CharT ch ); | (с C++11) (до C++20) | |
constexpr iterator insert( const_iterator pos, size_type count, CharT ch ); | (с C++20) | |
| (8) | ||
template< class InputIt > void insert( iterator pos, InputIt first, InputIt last ); | (до C++11) | |
template< class InputIt > iterator insert( const_iterator pos, InputIt first, InputIt last ); | (с C++11) (до C++20) | |
template< class InputIt > constexpr iterator insert( const_iterator pos, InputIt first, InputIt last ); | (с C++20) | |
| (9) | ||
iterator insert( const_iterator pos, std::initializer_list<CharT> ilist ); |
(с C++11) (до C++20) | |
constexpr iterator insert( const_iterator pos,
std::initializer_list<CharT> ilist );
| (с C++20) | |
| (10) | ||
template< class StringViewLike > basic_string& insert( size_type index, const StringViewLike& t ); |
(с C++17) (до C++20) | |
template< class StringViewLike > constexpr basic_string& insert( size_type index, const StringViewLike& t ); | (с C++20) | |
| (11) | ||
template< class StringViewLike >
basic_string& insert( size_type index, const StringViewLike& t,
size_type t_index, size_type count = npos ); |
(с C++17) (до C++20) | |
template< class StringViewLike >
constexpr basic_string& insert( size_type index, const StringViewLike& t,
size_type t_index, size_type count = npos );
| (с C++20) |
Вставляет символы в строку.
count копий символа ch в позицию index. s в позицию index. Длина строки определяется первым нулевым символом с использованием Traits::length(s). [s, s + count) в позицию index. Диапазон может содержать нулевые символы.str в позицию index.str.substr(s_index, count) в позицию index.ch перед символом, на который указывает pos.count копий символа ch перед элементом (если таковой имеется), на который указывает pos.[first, last) перед элементом (если таковой имеется), на который указывает pos, как если бы это было сделано посредством insert(pos - begin(), basic_string(first, last, get_allocator())). | Этот перегрузчик не участвует в разрешении перегрузки, если | (с C++11) |
ilist перед элементом (если таковой имеется), на который указывает pos.t в строковый вид sv как если бы это было сделано через std::basic_string_view<CharT, Traits> sv = t;, затем вставляет элементы из sv перед элементом (если таковой имеется), на который указывает index, как если бы это было сделано через insert(index, sv.data(), sv.size()).std::is_convertible_v<const StringViewLike&,
std::basic_string_view<CharT, Traits>> является true и std::is_convertible_v<const StringViewLike&, const CharT*> является false.t в строковый вид sv как если бы это было сделано через std::basic_string_view<CharT, Traits> sv = t;, затем вставляет, перед элементом (если таковой имеется), на который указывает index, символы из подстроки [t_index, t_index + count) объекта sv. - Если запрошенная подстрока выходит за пределы
sv, или еслиcount == npos, результирующая подстрока равна[t_index,sv.size()). - Если
t_index > sv.size(), или еслиindex > size(), выбрасывается исключениеstd::out_of_range.
std::is_convertible_v<const StringViewLike&,
std::basic_string_view<CharT, Traits>> является true и std::is_convertible_v<const StringViewLike&, const CharT*> является false.Если pos не является допустимым итератором в *this, поведение не определено.
Параметры
| index | - | позиция, в которую будет вставлено содержимое |
| pos | - | итератор перед которым будут вставлены символы |
| ch | - | символ для вставки |
| count | - | количество символов для вставки |
| s | - | указатель на строку символов для вставки |
| str | - | строка для вставки |
| first, last | - | диапазон, определяющий символы для вставки |
| s_index | - | позиция первого символа в str для вставки |
| ilist | - | список инициализации для вставки символов |
| t | - | объект (преобразуемый в std::basic_string_view) для вставки символов |
| t_index | - | позиция первого символа в t для вставки |
| Требования к типу | ||
-InputIt должен соответствовать требованиям LegacyInputIterator. |
||
Возвращаемое значение
*this
pos если символы не были вставлены (count == 0 или first == last или ilist.size() == 0).*this
Исключения
END_OF_DOCUMENT_MARKERВо всех случаях выбрасывает std::length_error если size() + ins_count > max_size(), где ins_count — число символов, которые будут вставлены.
| Во всех случаях, если std::allocator_traits<Allocator>::allocate вызывает исключение, оно перебрасывается. | (с C++20) |
Если по какой-либо причине возникает исключение, эта функция не оказывает никакого эффекта (гарантия сильной устойчивости к исключениям).
Пример
#include <cassert>
#include <iterator>
#include <string>
using namespace std::string_literals;
int main()
{
std::string s = "xmplr";
// insert(size_type index, size_type count, char ch)
s.insert(0, 1, 'E');
assert("Exmplr" == s);
// insert(size_type index, const char* s)
s.insert(2, "e");
assert("Exemplr" == s);
// insert(size_type index, string const& str)
s.insert(6, "a"s);
assert("Exemplar" == s);
// insert(size_type index, string const& str,
// size_type s_index, size_type count)
s.insert(8, " is an example string."s, 0, 14);
assert("Exemplar is an example" == s);
// insert(const_iterator pos, char ch)
s.insert(s.cbegin() + s.find_first_of('n') + 1, ':');
assert("Exemplar is an: example" == s);
// insert(const_iterator pos, size_type count, char ch)
s.insert(s.cbegin() + s.find_first_of(':') + 1, 2, '=');
assert("Exemplar is an:== example" == s);
// insert(const_iterator pos, InputIt first, InputIt last)
{
std::string seq = " string";
s.insert(s.begin() + s.find_last_of('e') + 1,
std::begin(seq), std::end(seq));
assert("Exemplar is an:== example string" == s);
}
// insert(const_iterator pos, std::initializer_list<char>)
s.insert(s.cbegin() + s.find_first_of('g') + 1, {'.'});
assert("Exemplar is an:== example string." == s);
}Отчеты об ошибках
Следующие отчеты об ошибках, изменяющие поведение, были применены ретроактивно к ранее опубликованным стандартам C++.
| Отчёт об ошибке | Применено к | Поведение, опубликованное как | Корректное поведение |
|---|---|---|---|
| LWG 7 | C++98 | перегрузка (8) ссылалась на несуществующую перегрузку | ссылается на перегрузку (4) корректно |
| LWG 847 | C++98 | не было гарантии устойчивости к исключениям | добавлена гарантия сильной устойчивости к исключениям |
| LWG 2946 | C++17 | перегрузка (10) вызывала неоднозначность в некоторых случаях | избегается путём создания шаблона |
См. также
|
(C++23) | вставляет диапазон символов (публичный член-функция) |
| добавляет символы в конец (публичный член-функция) |
|
| добавляет символ в конец (публичный член-функция) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/string/basic_string/insert