如何使用unique() algorithm? (C/C++) (STL)

來源:互聯網
上載者:User

此範例demo如何使用unique() algorithm。

 1/**//* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : GenericAlgo_unique.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use unique() algorithm
 7Release     : 12/11/2006 1.0
 8*/
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12
13using namespace std;
14
15int main() {
16  int ia[] = {5, 3, 1, 3, 2, 5};
17  vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
18
19  // sort() first, then use unique(), erase redundant
20  sort(ivec.begin(), ivec.end());
21  vector<int>::iterator iter = unique(ivec.begin(), ivec.end());
22  ivec.erase(iter, ivec.end());
23
24  copy(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, " "));
25
26  return 0;
27}

16,17行:使用array塞值再由array轉vector,只因為若用push_back()需要很多行,若配合array只要兩行即可。

20行:使用unique() algorithm只會將連續重複的資料挑出第一個,所以必須先將container sort()過,才能使用unique()。

21,22行:由於Algorithm nevers execute container operations的前提,unique() algorithm無法更改container的size,所以unique將多出來的element放到container的尾端,並傳回第一個redundant iterator,只要配合eras(),就可將redundant刪除。

所以sort->unique->erase是unique的標準動作。

執行結果

11 2 3 5 請按任意鍵繼續 . . .
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.