unique()函数

这篇博客是本人在学习算法中遇到的一个常用的函数,记录分享给大家

注意 :unique()函数是删除相邻的重复元素,并且返回的是去重范围后的第一个元素的地址,左闭右开

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
  vector<int> v={5,2,7,4,1,2,4,5,1};
  sort(v.begin(),v.end());
  
  auto pos=unique(v.begin(),v.end());
  v.erase(pos,v.end());
  for(auto e : v)
  {
    cout<<e<<" ";
  }
  
  
  int a[10]={1,3,2,4,6,2,1,1,5,2};
  sort(a,a+10);
  int n=unique(a,a+10)-a;//返回的是地址,所以要减去首元素的地址,得到n
  //注意nuique的返回的是删除完的数组,
  //的最后一个元素的下一个位置的地址
 
  for(int i=0;i<n;i++)
  {
    cout<<a[i]<<" ";
  }

  return 0;
}
相关推荐
吃好睡好便好1 天前
提取矩阵某一行或某一列元素
开发语言·人工智能·线性代数·算法·matlab·矩阵
deepin_sir1 天前
10 - 函数
开发语言·python
z落落1 天前
C#String字符串
开发语言·c#·php
wljy11 天前
二、进制状态转换
linux·运维·服务器·c语言·c++
猫头虎-前端技术1 天前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
云泽8081 天前
笔试算法 -位运算篇(二):从唯一字符到消失数字
c++·算法·位运算
枫叶林FYL1 天前
项目十:事件溯源仓储管理系统(WMS)仿真实现
开发语言·python
ʚ希希ɞ ྀ1 天前
不同路径|| -- dp
算法
繁华落尽,倾城殇?1 天前
[C++11] : atomic,nullptr,default/delete,enum class
开发语言·c++·c++11·nullptr·atomic·enum class·default/delete
01_ice1 天前
C语言数据在内存中的存储
c语言·开发语言