如何刪除container中重複的element? (C/C++) (STL)
时间:2010-10-26 来源:李sir
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}
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());
}
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。
相关阅读 更多 +