Namespaces
Variants

std::erase, std::erase_if(std::basic_string)

ja.cppreference.net より

 
 
 
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 を返す単項述語。

式 pred ( v ) は、 v の型(const修飾されている可能性もある) CharT のあらゆる引数に対して、 値カテゴリ に関わらず bool に変換可能でなければならず、 v を変更してはならない。したがって、 CharT & のパラメータ型は許可されない 。また、 CharT も、 CharT においてムーブがコピーと等価である場合を除き許可されない (C++11以降) 。 ​

戻り値

削除された要素の数。

計算量

線形。

注記

機能テスト マクロ 値 標準 機能
__cpp_lib_algorithm_default_value_type 202403 (C++26) リスト初期化 による std::erase

例

#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"

関連項目

文字を削除する
(パブリックメンバ関数)
特定の条件を満たす要素を削除する
(関数テンプレート & アルゴリズム関数オブジェクト)
特定の条件を満たす要素を削除する
(アルゴリズム関数オブジェクト)