名前空間
変種
操作

std::erase, std::erase_if(std::forward_list)

From cppreference.com
 
 
 
 
ヘッダ <forward_list> で定義
(1)
template< class T, class Alloc, class U >

std::forward_list<T, Alloc>::size_type

    erase( std::forward_list<T, Alloc>& c, const U& value );
(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以降)
1) コンテナから value と比較して等しいすべての要素を削除します。return c.remove_if([&](const auto& elem) -> bool { return elem == value; });と同等です。
2) コンテナから述語 pred を満たすすべての要素を削除します。return c.remove_if(pred);と同等です。

目次

[編集] パラメータ

c - 削除元のコンテナ
value - 削除する値
pred - 要素を削除すべき場合に true を返す単項述語。

pred(v) は、値カテゴリに関係なく、すべての引数 v(型は(おそらく const の)T)に対して bool に変換可能であり、v を変更しない必要があります。したがって、T& というパラメータ型は許可されません(T の場合、ムーブがコピーと同等である場合を除き、T も同様です(C++11 以降))。

[編集] 戻り値

削除された要素の数。

[編集] 計算量

線形。

注釈

std::forward_list::remove とは異なり、erase は異種型を受け入れ、== 演算子を呼び出す前にコンテナの値型への変換を強制しません。

機能テストマクロ 規格 機能
__cpp_lib_algorithm_default_value_type 202403 (C++26) アルゴリズム (1) のための リスト初期化

[編集]

#include <complex>
#include <iostream>
#include <numeric>
#include <string_view>
#include <forward_list>
 
void println(std::string_view comment, const auto& c)
{
    std::cout << comment << '[';
    bool first{true};
    for (const auto& x : c)
        std::cout << (first ? first = false, "" : ", ") << x;
    std::cout << "]\n";
}
 
int main()
{
    std::forward_list<char> cnt(10);
    std::iota(cnt.begin(), cnt.end(), '0');
    println("Initially, cnt = ", cnt);
 
    std::erase(cnt, '3');
    println("After erase '3', cnt = ", cnt);
 
    auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
    println("After erase all even numbers, cnt = ", cnt);
    std::cout << "Erased even numbers: " << erased << '\n';
 
    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
    println("After erase {4, 2}, nums = ", nums);
}

出力

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 として明示的に指定されています

[編集] 関連項目

特定の基準を満たす要素を削除する
(関数テンプレート) [編集]
特定の基準を満たす要素を削除する
(アルゴリズム関数オブジェクト)[編集]
特定の基準を満たす要素を削除する
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)