std::erase, std::erase_if(std::basic_string)
出自cppreference.com
| 在標頭 <string> 定義
|
||
| (1) | (C++20 起) (C++26 前) |
|
| (C++26 起) | ||
| |
(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 的) |
返回值
被擦除的元素數。
複雜度
線性。
註解
| 功能特性測試宏 | 值 | 標準 | 功能特性 |
|---|---|---|---|
__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"
參閱
| 移除滿足特定條件的元素 (函數模板) | |
(C++20)(C++20) |
移除滿足特定條件的元素 (算法函數對象) |