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

template <class ForwardIterator>
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 <iostream>
#include <vector>
#include <algorithm>
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
vector<int> myvector (myints,myints+);
vector<int>::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=;i<myvector.size();i++)
cout << " " << myvector[i];
cout<<endl; sort(myvector.begin(),myvector.end()); //先排序 it = unique (myvector.begin(), myvector.end(), myfunction);
// 使用比较函数,但此处是跟缺省的比较一样的。 myvector.resize( it - myvector.begin() ); // 10 20 30 cout << "second: myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl; return ;
} /*
输出:
first: myvector contains: 10 20 30 20 10
second: myvector contains: 10 20 30
*/

最新文章

  1. 【Alpha版本】冲刺阶段——Day 5
  2. HDU5831
  3. .net开发之我见,or实现 最简 优化法。knock out type convert 与我之简化orm的实现原理及实现细则,最简化开发法
  4. K-Anonymous Sequence(poj 3709)
  5. js_sl 延迟菜单
  6. C#中DataTable与实体集合通用转换(使用扩展方法)
  7. Codeforces Round #276 (Div. 1) A. Bits 二进制 贪心
  8. iphone6S“玫瑰金”的秘密——阳极氧化
  9. 洛谷比赛 Joe的数
  10. mvc和webapi同一解决方案调试办法
  11. Using SetWindowRgn
  12. case
  13. 数据库 MySQL基础知识
  14. [转]What is a WebRTC Gateway anyway? (Lorenzo Miniero)
  15. RxVolley使用文档 —— RxVolley = Volley + RxJava + OkHttp
  16. HTML 列表中的dl,dt,dd,ul,li,ol区别及应用
  17. Gym 101873G - Water Testing - [皮克定理]
  18. C# 动态方法和静态方法的区别
  19. python--第二天总结
  20. Asp.Net 之 禁用TextBox的记忆功能

热门文章

  1. 使用Reachability检测网格
  2. 什么是 Linux
  3. VMware View 要求操作句柄的状态错误
  4. TortoiseSVN如何更换或重置登录用户
  5. 对jquery插件Jcrop开发一个裁剪组件
  6. Spring注入内部的Beans
  7. Linux之时钟中断
  8. HDU 3118 Arbiter 判定奇圈
  9. 一览新的 Android Gradle 构建工具:新的 DSL 结构 和 Gradle 2.5
  10. HDU 4791 Alice&amp;#39;s Print Service 水二分