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;
}
相关推荐
NiceCloud喜云4 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
小羊在睡觉5 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
cjhbachelor5 小时前
c++继承
c++
3DVisionary5 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
AI玫瑰助手5 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
好评笔记5 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466855 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
油炸自行车5 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋5 小时前
C++14特性
开发语言·c++·c++14特性
_日拱一卒5 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先