std::list<T,Allocator>::unique
來自 cppreference.com
(1) | ||
void unique(); |
(C++20 前) | |
size_type unique(); |
(C++20 起) | |
(2) | ||
template< class BinaryPredicate > void unique( BinaryPredicate p ); |
(C++20 前) | |
template< class BinaryPredicate > size_type unique( BinaryPredicate p ); |
(C++20 起) | |
移除容器中所有*連續*的重複元素。每組相等元素中只保留第一個元素。僅使指向被移除元素的迭代器和引用失效。
1) 使用 operator== 比較元素。
2) 使用 p 比較元素。
如果相應的比較器未建立等價關係,則行為未定義。
目錄 |
[編輯] 引數
p | - | 二元謂詞,如果元素應被視為相等,則返回 true。 謂詞函式的簽名應等效於以下內容: bool pred(const Type1 &a, const Type2 &b); 儘管簽名不需要包含 const &,但該函式不得修改傳遞給它的物件,並且必須能夠接受型別為(可能是 const) |
型別要求 | ||
-BinaryPredicate 必須滿足 BinaryPredicate 的要求。 |
[編輯] 返回值
(無) |
(C++20 前) |
被移除元素的數量。 |
(C++20 起) |
[編輯] 複雜度
如果 empty() 為 true,則不執行比較。
否則,給定 N 作為 std::distance(begin(), end())
1) 恰好進行 N-1 次使用 operator== 的比較。
2) 恰好進行 N-1 次謂詞 p 的應用。
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_list_remove_return_type |
201806L |
(C++20) | 更改返回型別 |
[編輯] 示例
執行此程式碼
#include <iostream> #include <list> std::ostream& operator<< (std::ostream& os, std::list<int> const& container) { for (int val : container) os << val << ' '; return os << '\n'; } int main() { std::list<int> c{1, 2, 2, 3, 3, 2, 1, 1, 2}; std::cout << "Before unique(): " << c; const auto count1 = c.unique(); std::cout << "After unique(): " << c << count1 << " elements were removed\n"; c = {1, 2, 12, 23, 3, 2, 51, 1, 2, 2}; std::cout << "\nBefore unique(pred): " << c; const auto count2 = c.unique([mod = 10](int x, int y) { return (x % mod) == (y % mod); }); std::cout << "After unique(pred): " << c << count2 << " elements were removed\n"; }
輸出
Before unique(): 1 2 2 3 3 2 1 1 2 After unique(): 1 2 3 2 1 2 3 elements were removed Before unique(pred): 1 2 12 23 3 2 51 1 2 2 After unique(pred): 1 2 23 2 51 2 4 elements were removed
缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 1207 | C++98 | 尚不清楚迭代器 和/或引用是否會失效 |
僅使指向被移除元素的迭代器和 引用失效 |
[編輯] 另請參閱
移除一個範圍中的連續重複元素 (函式模板) |