名稱空間
變體
操作

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

來自 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) 對於型別為(可能 const)CharT 的每個引數 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 << "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"

[編輯] 參閱

移除滿足特定標準的元素
(函式模板) [編輯]
移除滿足特定標準的元素
(演算法函式物件)[編輯]