std::erase, std::erase_if(std::forward_list)
| ヘッダで定義 <forward_list>
|
||
template< class T, class Alloc, class U >
std::forward_list<T, Alloc>::size_type
erase( std::forward_list<T, Alloc>& c, const U& value );
|
(1) | (C++20 から) (C++26 まで) |
template< class T, class Alloc, class U = T >
std::forward_list<T, Alloc>::size_type
erase( std::forward_list<T, Alloc>& c, const U& value );
|
(C++26 から) | |
template< class T, class Alloc, class Pred >
std::forward_list<T, Alloc>::size_type
erase_if( std::forward_list<T, Alloc>& c, Pred pred );
|
(2) | (C++20 から) |
value と等しいと比較されるすべての要素を消去する。return c.remove_if([&](const auto& elem) -> bool { return elem == value; }); と同等。pred を満たすすべての要素を消去する。return c.remove_if(pred); と同等。パラメータ
| c | - | 要素を削除するコンテナ |
| value | - | 削除する値 |
| pred | - |
要素が削除されるべき場合に
true
を返す単項述語。
式
pred
(
v
)
は、
|
戻り値
削除された要素の数。
計算量
線形。
注記
std::forward_list::remove
とは異なり、
erase
は異種型を受け入れ、コンテナの値型への変換を強制せずに
==
演算子を呼び出します。
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_algorithm_default_value_type
|
202403
|
(C++26) |
リスト初期化
による
std::erase
|
例
#include <complex>
#include <numeric>
#include <print>
#include <forward_list>
template<typename T>
struct std::formatter<std::complex<T>, char>
{
template<class ParseContext>
constexpr ParseContext::iterator parse(ParseContext& ctx)
{
return ctx.begin();
}
template<class FmtContext>
FmtContext::iterator format(const auto& s, FmtContext& ctx) const
{
auto out{std::format("({},{})", s.real(), s.imag())};
return std::ranges::copy(std::move(out), ctx.out()).out;
}
};
int main()
{
std::forward_list<char> cnt(10);
std::iota(cnt.begin(), cnt.end(), '0');
std::println("Initially, cnt = {}", cnt);
std::erase(cnt, '3');
std::println("After erase '3', cnt = {}", cnt);
auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
std::println("After erase all even numbers, cnt = {}", cnt);
std::println("Erased even numbers: {}", erased);
std::forward_list<std::complex<double>> nums{{2, 2}, {4, 2}, {4, 8}, {4, 2}};
#ifdef __cpp_lib_algorithm_default_value_type
std::erase(nums, {4, 2});
#else
std::erase(nums, std::complex<double>{4, 2});
#endif
std::println("After erase {{4, 2}}, nums = {}", nums);
}
出力:\n
Initially, cnt = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After erase '3', cnt = [0, 1, 2, 4, 5, 6, 7, 8, 9]
After erase all even numbers, cnt = [1, 5, 7, 9]
Erased even numbers: 5
After erase {4, 2}, nums = [(2,2), (4,8)]
不具合報告
以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 4135 | C++20 |
ラムダ述語の戻り値型が
述語の引数から推論されていた |
戻り値型は
明示的に bool と指定される |
関連項目
| 特定の条件を満たす要素を削除する (パブリックメンバ関数) | |
| 特定の条件を満たす要素を削除する (関数テンプレート & アルゴリズム関数オブジェクト) | |
(C++20)(C++20) |
|
(C++20)(C++20) |
特定の条件を満たす要素を削除する (アルゴリズム関数オブジェクト) |