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, |
(начиная с C++17) (до C++20) |
|
template< class StringViewLike > constexpr basic_string& insert( size_type index, const StringViewLike& t, |
(начиная с C++20) | |
Вставляет символы в строку.
[
s,
s + count)
в позицию index. Диапазон может содержать нулевые символы.[
first,
last)
перед элементом (если есть), на который указывает pos, как если бы insert(pos - begin(), basic_string(first, last, get_allocator())).
Эта перегрузка не участвует в разрешении перегрузки, если |
(начиная с C++11) |
std::basic_string_view<CharT, Traits>> равно true и std::is_convertible_v<const StringViewLike&, const CharT*> равно false.
[
t_index,
t_index + count)
из sv.
- Если запрошенное подпредставление продолжается после конца sv или если count == npos, результирующее подпредставление будет
[
t_index,
sv.size())
. - Если t_index > sv.size() или index > size(), генерирует std::out_of_range.
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 | — | std::initializer_list из которого вставлять символы |
t | — | объект (конвертируемый в std::basic_string_view) из которого вставлять символы |
t_index | — | позиция первого символа в t для вставки |
Требования к типам | ||
-InputIt должен соответствовать требованиям LegacyInputIterator.
|
[править] Возвращаемое значение
[править] Исключения
Во всех случаях генерирует 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) |
вставляет диапазон символов (public функция-элемент) |
добавляет символы в конец (public функция-элемент) | |
добавляет символ в конец (public функция-элемент) |