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

出自cppreference.com
 
 
 
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 的一元謂詞。

對每個(可為 const 的) CharT 類型參數 v ,表達式 pred(v) 必須可轉換到 bool,無關乎值類別,而且必須不修改 v 。從而不允許 CharT& 類型參數,亦不允許 CharT ,除非對 CharT 而言移動等價於複製(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 << "起初,word = " << std::quoted(word) << '\n';

    std::erase(word, 'l');
    std::cout << "擦除 'l' 后:" << std::quoted(word) << '\n';

    auto erased = std::erase_if(word, [](char x)
    {
        return x == 'a' or x == 'r' or x == 't';
    });

    std::cout << "擦除全部 'a'、'r' 和 't' 后:" << std::quoted(word) << '\n';
    std::cout << "被擦除符号计数:" << erased << '\n';

#if __cpp_lib_algorithm_default_value_type
    std::erase(word, {'g'});
    std::cout << "擦除 {'g'} 后: " << std::quoted(word) << '\n';
#endif
}

輸出:

起初,word = "startling"
擦除 'l' 后:"starting"
擦除全部 'a'、'r' 和 't' 后:"sing"
被擦除符号计数:4
擦除 {'g'} 后: "sin"

參閱

移除滿足特定條件的元素
(函數模板) [編輯]
移除滿足特定條件的元素
(算法函數對象) [編輯]