博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
STL Algorithms 之 unique
阅读量:4671 次
发布时间:2019-06-09

本文共 1462 字,大约阅读时间需要 4 分钟。

C++的文档中说,STL中的unique是类似于这样实现的:

 

template 
ForwardIterator unique ( ForwardIterator first, ForwardIterator last ){ ForwardIterator result=first; while (++first != last) { if (!(*result == *first)) // or: if (!pred(*result,*first)) for the pred version *(++result)=*first; } return ++result;}

 

仔细一看就知道,它并不是帮你直接把一个数组中所有重复的元素除去,而是对数组扫描一次,只看当前元素和前面一个元素,如果当前值和前面的值相等,那么跳过,否则就把这个值算上,迭代器递增,最后返回给你一个位置,表示我扫描到多少个当前值与其前面一个元素值不同的元素。

所以,要真正利用好unique,我们必须先对我们所需要进行unique操作的数组排序,然后再使用unique。

这样以后其实还是不满足我们的要求的,因为实际上unique函数实现的只是把不同的元素“unique”放到数组的前面,而数组的后面还有一段重复的没有去掉。这个时候就可以利用到unique函数的返回值啦,它返回的就是重复元素出现的第一个位置。

另外,unique函数可以接受两个参数(数组的开头,数组的末尾),也可以接受三个参数(数组的开头,数组的末尾,两个元素的比较(即定义怎样算元素相等))

看一下实例吧:

// resizing vector#include 
#include
#include
using namespace std;bool myfunction (int i, int j) { return (i==j);}int main () { int myints[] = {
10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10 vector
myvector (myints,myints+9); vector
::iterator it; it = unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ? ? ? ? //尖所指即it的位置 // ^ myvector.erase( it , myvector.end() ); // 第一种去掉末尾的方法 cout << "first: myvector contains:"; for (int i=0;i

 

转载于:https://www.cnblogs.com/bofengyu/p/4755733.html

你可能感兴趣的文章
css实现背景图片模糊
查看>>
什么是runtime?什么是webgl?
查看>>
秋季学习总结
查看>>
categorical_crossentropy VS. sparse_categorical_crossentropy
查看>>
强引用,弱引用,4种Java引用浅解(涉及jvm垃圾回收)
查看>>
多线程如何确定线程数
查看>>
UGUI RectTransform
查看>>
学前班
查看>>
手把手教您扩展虚拟内存
查看>>
android-samples-mvp
查看>>
oracle 11g r2安装
查看>>
关于自关联1
查看>>
存储控制器、MMU、flash控制器介绍
查看>>
hdu-1814(2-sat)
查看>>
自我反省
查看>>
反射,得到Type引用的三种方式
查看>>
pl sql练习(2)
查看>>
Problem B: 判断回文字符串
查看>>
谷歌浏览器,添加默认搜索引擎的搜索地址
查看>>
数据结构化与保存
查看>>