公共成員函式
<list>

std::list::unique

(1)
void unique();
(2)
template <class BinaryPredicate>  void unique (BinaryPredicate binary_pred);
移除重複值
無引數版本 (1),從容器中每組連續的相同元素中移除除第一個元素外的所有元素。

請注意,只有當一個元素與它緊鄰的前一個元素比較相等時,它才會被從 list 容器中移除。因此,此函式對於已排序的列表特別有用。

第二個版本 (2),接受一個特定的比較函式作為引數,該函式用於確定元素的“唯一性”。實際上,可以實現任何行為(而不僅僅是相等比較),但請注意,該函式將呼叫binary_pred(*i,*(i-1))對於所有元素對(其中i是元素的迭代器,從第二個開始)並將i從列表中移除,如果謂詞返回true.

被移除的元素將被銷燬。

引數

binary_pred
二元謂詞,接受與 list 中包含的型別相同的兩個值,如果需要從容器中移除第一個引數所傳遞的元素,則返回truetrue,否則返回 false。
這應該是一個函式指標或一個函式物件。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// list::unique
#include <iostream>
#include <cmath>
#include <list>

// a binary predicate implemented as a function:
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }

// a binary predicate implemented as a class:
struct is_near {
  bool operator() (double first, double second)
  { return (fabs(first-second)<5.0); }
};

int main ()
{
  double mydoubles[]={ 12.15,  2.72, 73.0,  12.77,  3.14,
                       12.77, 73.35, 72.25, 15.3,  72.25 };
  std::list<double> mylist (mydoubles,mydoubles+10);
  
  mylist.sort();             //  2.72,  3.14, 12.15, 12.77, 12.77,
                             // 15.3,  72.25, 72.25, 73.0,  73.35

  mylist.unique();           //  2.72,  3.14, 12.15, 12.77
                             // 15.3,  72.25, 73.0,  73.35

  mylist.unique (same_integral_part);  //  2.72,  3.14, 12.15
                                       // 15.3,  72.25, 73.0

  mylist.unique (is_near());           //  2.72, 12.15, 72.25

  std::cout << "mylist contains:";
  for (std::list<double>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

輸出
mylist contains: 2.72 12.15 72.25


複雜度

時間複雜度為容器大小減一的線性時間。

迭代器有效性

引用被函式移除的元素的迭代器、指標和引用將失效。
所有其他迭代器、指標和引用保持其有效性。

資料競爭

容器被修改。
被移除的元素被修改。併發訪問或修改其他元素是安全的,儘管遍歷容器則不安全。

異常安全

如果 binary_pred 或元素比較保證不丟擲異常,則函式絕不丟擲異常(無丟擲保證)。
否則,如果丟擲異常,容器將處於有效狀態(基本保證)。

另見