std::list<T,Allocator>::remove, remove_if
來自 cppreference.com
(1) | ||
void remove( const T& value ); |
(C++20 前) | |
size_type remove( const T& value ); |
(C++20 起) | |
(2) | ||
template< class UnaryPredicate > void remove_if( UnaryPredicate p ); |
(C++20 前) | |
template< class UnaryPredicate > size_type remove_if( UnaryPredicate p ); |
(C++20 起) | |
移除所有滿足特定條件的元素。只使被移除元素的迭代器和引用失效。
1) 移除所有等於 value 的元素(使用 operator==)。
2) 移除所有使謂詞 p 返回 true 的元素。
目錄 |
[edit] 引數
value | - | 要移除的元素的值 |
p | - | 一元謂詞,如果元素應該被移除,則返回 true。 對於型別為(可能是 const) |
型別要求 | ||
-UnaryPredicate 必須滿足 Predicate 的要求。 |
[edit] 返回值
(無) |
(C++20 前) |
被移除元素的數量。 |
(C++20 起) |
[edit] 複雜度
給定 N 為 std::distance(begin(), end())
1) 使用 operator== 進行精確 N 次比較。
2) 精確 N 次謂詞 p 的應用。
[edit] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_list_remove_return_type |
201806L |
(C++20) | 更改返回型別 |
[edit] 示例
執行此程式碼
#include <list> #include <iostream> int main() { std::list<int> l = {1, 100, 2, 3, 10, 1, 11, -1, 12}; auto count1 = l.remove(1); std::cout << count1 << " elements equal to 1 were removed\n"; auto count2 = l.remove_if([](int n){ return n > 10; }); std::cout << count2 << " elements greater than 10 were removed\n"; std::cout << "Finally, the list contains: "; for (int n : l) std::cout << n << ' '; std::cout << '\n'; }
輸出
2 elements equal to 1 were removed 3 elements greater than 10 were removed Finally, the list contains: 2 3 10 -1
缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 1207 | C++98 | 關於迭代器和/或引用是否會失效尚不明確 和/或引用是否會失效 |
只使被移除元素的迭代器和引用失效 引用失效 |
[edit] 另請參閱
移除滿足特定標準的元素 (函式模板) |