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

本文通过一个C++示例演示了STL中unique()算法的使用方法。首先,将数组转换为vector,然后对其进行排序,接着使用unique()算法去除连续重复元素,并最后使用erase()删除冗余项。这一过程展示了如何有效去除容器中的重复元素。

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

 1ExpandedBlockStart.gifContractedBlock.gif/**//* 
 2InBlock.gif(C) OOMusou 2006 http://oomusou.cnblogs.com
 3InBlock.gif
 4InBlock.gifFilename    : GenericAlgo_unique.cpp
 5InBlock.gifCompiler    : Visual C++ 8.0 / ISO C++
 6InBlock.gifDescription : Demo how to use unique() algorithm
 7InBlock.gifRelease     : 12/11/2006 1.0
 8ExpandedBlockEnd.gif*/

 9None.gif#include <iostream>
10None.gif#include <algorithm>
11None.gif#include <vector>
12None.gif
13None.gifusing namespace std;
14None.gif
15ExpandedBlockStart.gifContractedBlock.gifint main() dot.gif{
16ExpandedSubBlockStart.gifContractedSubBlock.gif  int ia[] = dot.gif{531325};
17InBlock.gif  vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
18InBlock.gif
19InBlock.gif  // sort() first, then use unique(), erase redundant
20InBlock.gif  sort(ivec.begin(), ivec.end());
21InBlock.gif  vector<int>::iterator iter = unique(ivec.begin(), ivec.end());
22InBlock.gif  ivec.erase(iter, ivec.end());
23InBlock.gif
24InBlock.gif  copy(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, " "));
25InBlock.gif
26InBlock.gif  return 0;
27ExpandedBlockEnd.gif}


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的標準動作。

執行結果

1None.gif1 2 3 5 請按任意鍵繼續 . . .


Keyword
STL, algorithm, example, sort, unique, erase

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值