C++ 列表庫 - unique() 函式



描述

C++ 函式std::list::unique() 刪除列表中所有連續的重複元素。它使用二元謂詞進行比較。

宣告

以下是來自 std::list 標頭檔案的 std::list::unique() 函式的宣告。

C++98

template <class BinaryPredicate>
void unique (BinaryPredicate binary_pred);

引數

binary_pred − 二元謂詞,如果元素應被視為相等則返回 true。它具有以下原型。

bool pred(const Type1 &arg1, const Type2 &arg2);

返回值

異常

此成員函式從不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例顯示了 std::list::unique() 函式的用法。

#include <iostream>
#include <list>

using namespace std;

/* Ignore sign of the value */
bool pred(int a, int b) {
   return (abs(a) == abs(b));
}

int main(void) {
   list <int> l = {1, -1, -1, -1, 2, 2, -2, -2, 3, -4, 4, -5, -5, 5};

   cout << "List elements before unique operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   /* Ignore sign of the value */
   l.unique(pred);

   cout << "List elements after unique operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

List elements before unique operation
1
-1
-1
-1
2
2
-2
-2
3
-4
4
-5
-5
5
List elements after unique operation
1
2
3
-4
-5
list.htm
廣告