此範例demo如何使用unique() algorithm。
 1unique函数_unique/* 
 2unique函数_休闲_03(C) OOMusou 2006 [url]http://oomusou.cnblogs.com[/url]
 3unique函数_休闲_03
 4unique函数_休闲_03Filename    : GenericAlgo_unique.cpp
 5unique函数_休闲_03Compiler    : Visual C++ 8.0 / ISO C++
 6unique函数_休闲_03Description : Demo how to use unique() algorithm
 7unique函数_休闲_03Release     : 12/11/2006 1.0
 8unique函数_休闲_09*/

 9unique函数_函数_10#include <iostream>
10unique函数_函数_10#include <algorithm>
11unique函数_函数_10#include <vector>
12unique函数_函数_10
13unique函数_函数_10using namespace std;
14unique函数_函数_10
15unique函数_职场_16int main() {
16unique函数_职场_19  int ia[] = {531325};
17unique函数_休闲_03  vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
18unique函数_休闲_03
19unique函数_休闲_03  // sort() first, then use unique(), erase redundant
20unique函数_休闲_03  sort(ivec.begin(), ivec.end());
21unique函数_休闲_03  vector<int>::iterator iter = unique(ivec.begin(), ivec.end());
22unique函数_休闲_03  ivec.erase(iter, ivec.end());
23unique函数_休闲_03
24unique函数_休闲_03  copy(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, " "));
25unique函数_休闲_03
26unique函数_休闲_03  return 0;
27unique函数_休闲_09}

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的標準動作。
執行結果
1unique函数_函数_101 2 3 5 請按任意鍵繼續 . . .