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



描述

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

宣告

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

C++98

void unique();

引數

返回值

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <list>

using namespace std;

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

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

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

   l.unique();

   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
2
2
3
4
5
5
List elements after unique operation
1
2
3
4
5
list.htm
廣告

© . All rights reserved.