std::erase, std::erase_if(std::basic_string)
Определено в заголовочном файле <string> | ||
|---|---|---|
template< class CharT, class Traits, class Alloc, class U >
constexpr std::basic_string<CharT, Traits, Alloc>::size_type
erase( std::basic_string<CharT, Traits, Alloc>& c, const U& value );
| (1) |
(начиная с C++20) (до C++26) |
template< class CharT, class Traits, class Alloc, class U = CharT >
constexpr std::basic_string<CharT, Traits, Alloc>::size_type
erase( std::basic_string<CharT, Traits, Alloc>& c, const U& value );
| (начиная с C++26) | |
template< class CharT, class Traits, class Alloc, class Pred >
constexpr std::basic_string<CharT, Traits, Alloc>::size_type
erase_if( std::basic_string<CharT, Traits, Alloc>& c, Pred pred );
| (2) | (начиная с C++20) |
1) Удаляет из контейнера все элементы, равные
value. Эквивалентно auto it = std::remove(c.begin(), c.end(), value); auto r = c.end() - it; c.erase(it, c.end()); return r;
2) Удаляет из контейнера все элементы, удовлетворяющие предикату
pred. Эквивалентно auto it = std::remove_if(c.begin(), c.end(), pred); auto r = c.end() - it; c.erase(it, c.end()); return r;
Параметры
| c | - | контейнер, из которого выполняется удаление |
| value | - | удаляемое значение |
| pred | - | унарный предикат, возвращающий true, если элемент следует удалить. Выражение |
Возвращаемое значение
Количество удалённых элементов.
Сложность
Линейная.
Примечания
| Макрос проверки поддержки возможности | Значение | Стандарт | Возможность |
|---|---|---|---|
__cpp_lib_algorithm_default_value_type | 202403 | (C++26) | Инициализация списком для алгоритма (1) |
Пример
#include <iomanip>
#include <iostream>
#include <string>
int main()
{
std::string word{"startling"};
std::cout << "Initially, word = " << std::quoted(word) << '\n';
std::erase(word, 'l');
std::cout << "After erase 'l': " << std::quoted(word) << '\n';
auto erased = std::erase_if(word, [](char x)
{
return x == 'a' or x == 'r' or x == 't';
});
std::cout << "After erase all 'a', 'r', and 't': " << std::quoted(word) << '\n';
std::cout << "Erased symbols count: " << erased << '\n';
#if __cpp_lib_algorithm_default_value_type
std::erase(word, {'g'});
std::cout << "After erase {'g'}: " << std::quoted(word) << '\n';
#endif
}
Возможный вывод:
Initially, word = "startling"
After erase 'l', word = "starting"
After erase all 'a', 'r', and 't': "sing"
Erased symbols count: 4
After erase {'g'}: "sin"
См. также
| удаляет символы (открытая функция-член) |
|
| удаляет элементы, удовлетворяющие заданным критериям (шаблон функции и объект-функция алгоритма) |
|
|
(C++20)(C++20) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/string/basic_string/erase2