std::erase, std::erase_if(std::basic_string)
來自 cppreference.com
< cpp | string | basic_string
定義於標頭檔案 <string> |
||
(1) | ||
template< class CharT, class Traits, class Alloc, class U > constexpr std::basic_string<CharT, Traits, Alloc>::size_type |
(C++20 起) (直到 C++26) |
|
template< class CharT, class Traits, class Alloc, class U = CharT > constexpr std::basic_string<CharT, Traits, Alloc>::size_type |
(C++26 起) | |
template< class CharT, class Traits, class Alloc, class Pred > constexpr std::basic_string<CharT, Traits, Alloc>::size_type |
(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) |
[編輯] 返回值
被刪除元素的數量。
[編輯] 複雜度
線性。
注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__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"
[編輯] 參閱
移除滿足特定標準的元素 (函式模板) | |
(C++20)(C++20) |
移除滿足特定標準的元素 (演算法函式物件) |