如何刪除container中重複的element? (C/C++) (STL)

來源:互聯網
上載者:User

Abstract
STL並沒有提供這樣的algorithm,透過簡單的方法,就可以達成這個需求。

Sample Code

 1/**//* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : GenericAlgo_eliminate_duplicate.cpp
 5Compiler    : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
 6Description : Demo how to duplicated element in container
 7Release     : 05/27/2007 1.0
 8*/
 9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13using namespace std;
14
15template<typename T>
16inline void eliminate_duplicates(T& c) {
17  sort(c.begin(), c.end());
18  c.erase(unique(c.begin(), c.end()), c.end());  
19}
20
21int main() {
22  int ia[] = {1, 1, 2, 3, 3};
23  vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
24  
25  eliminate_duplicates(ivec);
26  copy(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, " "));
27}

執行結果

1 2 3 

15行

template<typename T>
inline void eliminate_duplicates(T& c) {
  sort(c.begin(), c.end());
  c.erase(unique(c.begin(), c.end()), c.end());  
}

由於要使用unique(),必須先經過sort()才有用,unique()會將重複的element放到container後面,並且將pointer指向重複的第一個element,erase()將從這個element,一直刪除到container最後,如此只會留下不重複的element。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.