删除vector中的重复数据(unique)
2016-05-04 19:47
627 查看
#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返回的迭代器指向超出无重复的元素范围末端的下一个位置。
相关文章推荐
- POJ 1122 FDNY to the Rescue!(最短路径)
- iOS UIKit:viewController之动画(5)
- SoapUI测试WSDL文件
- Learn how to Use UIPageViewController in iOS
- iOS UIKit:viewController之Segues (4)
- 十大滤波算法程序大全(Arduino精编无错版)
- Xcode多种Build Configuration配置使用
- BurpSuite的使用总结
- UESTC 482 Charitable Exchange(优先队列+bfs)
- UESTC 482 Charitable Exchange(优先队列+bfs)
- GUI for git|SourceTree|入门基础
- [2016,CVPR] Learning Deep Feature Representations with Domain Guided Dropout for Person Re-id
- 优化UITableViewCell高度计算
- <LeetCode OJ> 347. Top K Frequent Elements
- 颜色转变图片
- UIBezierPath详解
- compileSdkVersion、buildToolsVersion、minSdkVersion、targetSdkVersion
- android 基础 LoaderManager 用来不堵塞UI主线程
- Java进阶学习第十天——request&response
- 七周七种前端框架四:Vue.js 构建大型应用