public member function
<forward_list>

std::forward_list::unique

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

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

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

被移除的元素將被銷燬。

引數

binary_pred
二元謂詞,它接受與forward_list中包含的元素型別相同的兩個值,如果則從forward_list中移除元素。should remove the element passed as first argument from the container, and false otherwise.
這應該是一個函式指標或函式物件。

返回值



示例

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
// forward_list::unique
#include <iostream>
#include <cmath>
#include <forward_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:
class is_near_class
{
public:
  bool operator() (double first, double second)
  { return (fabs(first-second)<5.0); }
} is_near_object;

int main ()
{

  std::forward_list<double> mylist = { 15.2, 73.0, 3.14, 15.85, 69.5,
                                       73.0, 3.99, 15.2, 69.2,  18.5 };

  mylist.sort();                       //   3.14,  3.99, 15.2, 15.2, 15.85
                                       //  18.5,  69.2,  69.5, 73.0, 73.0

  mylist.unique();                     //   3.14,  3.99, 15.2, 15.85
                                       //  18.5,  69.2,  69.5, 73.0

  mylist.unique (same_integral_part);  //  3.14, 15.2, 18.5,  69.2, 73.0

  mylist.unique (is_near_object);      //  3.14, 15.2, 69.2

  std::cout << "mylist contains:";
  for (double& x: mylist) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

輸出
mylist contains: 3.14 15.2 69.2


複雜度

線性複雜度,與容器大小減一成正比。

迭代器有效性

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

資料競爭

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

異常安全

如果binary_pred或元素的比較被保證不會丟擲異常,則函式永遠不會丟擲異常(無丟擲保證)。
否則,如果丟擲異常,容器將保持在有效狀態(基本保證)。

另見