刪除vector中的重復數據(unique)
阿新 • • 發佈:2018-04-07
com itl begin Go IT rep main sort函數 功能
[cpp] view plain copy
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <assert.h>
- using namespace std;
- template<typename T>
- inline void deduplication(T& c)
- {
- sort(c.begin(), c.end());
- T::iterator new_end = unique(c.begin(), c.end());//"刪除"相鄰的重復元素
- c.erase(new_end, c.end());//刪除(真正的刪除)重復的元素
- }
- int main()
- {
- int ary[] = {1, 1, 2, 3, 2, 4, 3};
- vector<int> vec(ary, ary + sizeof(ary) / sizeof(int));
- //
- deduplication(vec);
- //
- copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
- system("pause");
- return 0;
- }
註:unique函數功能是去除相鄰的重復元素,註意是相鄰,所以必須先使用sort函數。還有一個容易忽視的特性是它並不真正把重復的元素刪除。之所以說比不真正把重復的元素刪除,因為unique實際上並沒有刪除任何元素,而是將無重復的元素復制到序列的前段,從而覆蓋相鄰的重復元素。unique返回的叠代器指向超出無重復的元素範圍末端的下一個位置。
https://blog.csdn.net/hellokandy/article/details/51317593
刪除vector中的重復數據(unique)