一.unique函数

类属性算法unique的作用是从输入序列中“删除”所有相邻的重复元素

该算法删除相邻的重复元素,然后重新排列输入范围内的元素,并且返回一个迭代器(容器的长度没变,只是元素顺序改变了),表示无重复的值范围得结束。

 1 // sort words alphabetically so we can find the duplicates
2 sort(words.begin(), words.end());
3 /* eliminate duplicate words:
4 * unique reorders words so that each word appears once in the
5 * front portion of words and returns an iterator one past the
6 unique range;
7 * erase uses a vector operation to remove the nonunique elements
8 */
9 vector<string>::iterator end_unique = unique(words.begin(), words.end());
10 words.erase(end_unique, words.end());

在STL中unique函数是一个去重函数, unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

若调用sort后,vector的对象的元素按次序排列如下:

sort  jumps  over quick  red  red  slow  the  the turtle

则调用unique后,vector中存储的内容是:

注意,words的大小并没有改变,依然保存着10个元素;只是这些元素的顺序改变了。调用unique“删除”了相邻的重复值。给“删除”加上引号是因为unique实际上并没有删除任何元素,而是将无重复的元素复制到序列的前段,从而覆盖相邻的重复元素。unique返回的迭代器指向超出无重复的元素范围末端的下一个位置。

注意:算法不直接修改容器的大小。如果需要添加或删除元素,则必须使用容器操作。

 1 #include <iostream>
2 #include <cassert>
3 #include <algorithm>
4 #include <vector>
5 #include <string>
6 #include <iterator>
7 using namespace std;
8
9 int main()
10 {
11 //cout<<"Illustrating the generic unique algorithm."<<endl;
12 const int N=11;
13 int array1[N]={1,2,0,3,3,0,7,7,7,0,8};
14 vector<int> vector1;
15 for (int i=0;i<N;++i)
16 vector1.push_back(array1[i]);
17
18 vector<int>::iterator new_end;
19 new_end=unique(vector1.begin(),vector1.end()); //"删除"相邻的重复元素
20 assert(vector1.size()==N);
21
22 vector1.erase(new_end,vector1.end()); //删除(真正的删除)重复的元素
23 copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," "));
24 cout<<endl;
25
26 return 0;
27 }


最新文章

  1. ASP.NET MVC5+EF6+EasyUI 后台管理系统(31)-MVC使用RDL报表
  2. Android Studio同时打开多个项目
  3. Win7 64位 VS2015及MinGW环境编译矢量库agg-2.5和cairo-1.14.6
  4. Codeforces 486E LIS of Sequence --树状数组求LIS
  5. C# 6.0可能的新特性
  6. IOS基础之 (七) 分类Category
  7. D django 用户认证系统
  8. dede上怎么让所有链接在新窗口打开
  9. 管理员必须掌握的八个cmd命令
  10. js 数字
  11. 关于 parseInt 的一道有意思的面试题
  12. @为Java注解
  13. Cocos2D v3.4.9粒子效果不能显示的原因分析及解决办法
  14. Chapter 2 User Authentication, Authorization, and Security(10):创建包含数据库
  15. Tomcat和Weblogic部署纯html文件
  16. 第二次作业——分布式版本控制系统Git的安装与使用
  17. db2 SQL6036N解决办法
  18. python学习笔记_week10
  19. js-JavaScript常见的创建对象的几种方式
  20. pyobjc-framework-Cocoa 5.1.2

热门文章

  1. 10.6Java学习
  2. vijos题解
  3. 解决使用tomcat服务器发布web项目时出现URL中文乱码的问题
  4. PHP设计模式之模板方法模式
  5. lua自写限制并发访问模块
  6. 『Python』列表生成式、生成器与迭代器
  7. turtle setup和screensize
  8. P6800-[模板]Chirp Z-Transform【NTT】
  9. WPF进阶技巧和实战01-小技巧
  10. 阿里云ECS服务器Centos中安装SQL Server(破解内存限制)