删除vector中的重复数据(unique)

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


注:unique函数功能是去除相邻的重复元素,注意是相邻,所以必须先使用sort函数。还有一个容易忽视的特性是它并不真正把重复的元素删除。之所以说比不真正把重复的元素删除,因为unique实际上并没有删除任何元素,而是将无重复的元素复制到序列的前段,从而覆盖相邻的重复元素。unique返回的迭代器指向超出无重复的元素范围末端的下一个位置。

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

原文地址:https://www.cnblogs.com/findumars/p/8732304.html