std::erase、std::erase_if(std::basic_string)
From cppreference.com
< cpp | string | basic string
| ヘッダ <string> で定義 |
||
| (1) | ||
template< class CharT, class Traits, class Alloc, class U > constexpr std::basic_string<CharT, Traits, Alloc>::size_type |
(C++20以降) (C++26まで) |
|
| template< class CharT, class Traits, class Alloc, class U = CharT > constexpr std::basic_string<CharT, Traits, Alloc>::size_type |
(C++26以降) | |
| template< class CharT, class Traits, class Alloc, class Pred > constexpr std::basic_string<CharT, Traits, Alloc>::size_type |
(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 を返す単項述語。 式 pred(v) は、値カテゴリに関わらず、すべての引数 |
[編集] 戻り値
削除された要素の数。
[編集] 計算量
線形。
注釈
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__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) |
特定の基準を満たす要素を削除する (アルゴリズム関数オブジェクト) |