1. 程式人生 > >刪除vector中的重復數據(unique)

刪除vector中的重復數據(unique)

com itl begin Go IT rep main sort函數 功能

[cpp] view plain copy
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <assert.h>
  5. using namespace std;
  6. template<typename T>
  7. inline void deduplication(T& c)
  8. {
  9. sort(c.begin(), c.end());
  10. T::iterator new_end = unique(c.begin(), c.end());//"刪除"相鄰的重復元素
  11. c.erase(new_end, c.end());//刪除(真正的刪除)重復的元素
  12. }
  13. int main()
  14. {
  15. int ary[] = {1, 1, 2, 3, 2, 4, 3};
  16. vector<int> vec(ary, ary + sizeof(ary) / sizeof(int));
  17. //
  18. deduplication(vec);
  19. //
  20. copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
  21. system("pause");
  22. return 0;
  23. }


註:unique函數功能是去除相鄰的重復元素,註意是相鄰,所以必須先使用sort函數。還有一個容易忽視的特性是它並不真正把重復的元素刪除。之所以說比不真正把重復的元素刪除,因為unique實際上並沒有刪除任何元素,而是將無重復的元素復制到序列的前段,從而覆蓋相鄰的重復元素。unique返回的叠代器指向超出無重復的元素範圍末端的下一個位置。

https://blog.csdn.net/hellokandy/article/details/51317593

刪除vector中的重復數據(unique)