名前空間
変種
操作

std::erase、std::erase_if(std::basic_string)

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
定数
非メンバ関数
erase(std::basic_string)erase_if(std::basic_string)
(C++20)(C++20)
I/O
比較
(C++20まで)(C++20まで)(C++20まで)(C++20まで)(C++20まで)(C++20)
数値変換
(C++11)(C++11)(C++11)
(C++11)(C++11) 
(C++11)(C++11)(C++11)
(C++11)
(C++11)
リテラル
ヘルパークラス
推論ガイド (C++17)
 
ヘッダ <string> で定義
(1)
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 );
(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& は許可されません、また CharTCharT のムーブがコピーと同等でない限り許可されません(C++11 以降)。​

[編集] 戻り値

削除された要素の数。

[編集] 計算量

線形。

注釈

機能テストマクロ 規格 機能
__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"

[編集] 関連項目

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