C++ STL 中 unique() 函数详解

C++ STL 中 unique() 函数详解

1.简要说明

unique()函数用于删除序列中重复相邻元素,注意一定是相邻元素(所以使用unique()函数前一般都需要进行排序),而且这里的删除也不是直接删除(会返回一个迭代器,之后再使用erase()函数进行删除)

2.函数原型

iterator unique(iterator it_1,iterator it_2,bool MyFunc);
  • 前两个参数都是迭代器,表示对区间[it_1, it_2)内进行去重(左闭右开,和许多其他STL函数都一样)
  • 最后一个参数时自定义的函数,这里不过多介绍,可以参考http://www.cplusplus.com/reference/algorithm/unique/
  • 注意时删除区间[it_1, it_2)重复相邻元素

3.原理介绍

其实原理比较简单,就是不断的将后面不重复的元素覆盖前面重复的元素,并且返回最后一个不重复元素的坐标(迭代器)

其实就是等价于下面的代码:

iterator My_Unique (iterator first, iterator last)
{
    
    
if (first==last)
    return last;  // 只有一个元素的情况
iterator result = first;  // 从第一个元素开始
while (++first != last)   // 直到最后一个元素
{
    
    
if (*result != *first)    // 找到了一个不重复的元素
	*(++result)=*first;   // 覆盖前面的元素
}
return ++result;          // 返回最后不重复元素的坐标
}

4.使用示例

使用unique()函数进行去重

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;


int main()
{
    
    
    int myints[] = {
    
    1,2,3,1,1};
    int len = sizeof(myints)/sizeof(int);
    vector<int> vec(myints, myints + len);
    sort(vec.begin(), vec.end());
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
    for(int x : vec)
        cout << x << ",";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44338712/article/details/107876510