[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
unique(C++)函数的功能是元素去重。即”删除”序列中所有相邻的重复元素(只保留一个)。
此处的删除,并不是真的删除,就是把重复元素的位置让不重复元素使用。
由于它”删除”的是相邻的重复元素,所以在使用unique函数之前,一般都会将目标序列进行排序。
下面来一道洛谷例题:
题目描述
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了NN个11到10001000之间的随机整数(N≤100)(N≤100),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。
输入格式
输入有两行,第11行为11个正整数,表示所生成的随机数的个数NN
第22行有NN个用空格隔开的正整数,为所产生的随机数。
输出格式
输出也是两行,第11行为11个正整数MM,表示不相同的随机数的个数。
第22行为MM个用空格隔开的正整数,为从小到大排好序的不相同的随机数。
输入输出样例
输入 #1复制
10 20 40 32 67 40 20 89 300 400 15
输出 #1复制
8 15 20 32 40 67 89 300 400 #include<bits/stdc++.h> using namespace std; int
main() { int n,i; cin>>n; int a[100000];//我就是定义一个足够大的数组,这里不是重点 for(i=0;i<n;i++)
{ cin>>a[i]; } sort(a,a+n);//这里就是排序 int x=unique(a,a+n)-a;//关键点来了
cout<<x<<endl;//x就是排序后没有重复元素的长度 for(i=0;i<x;i++) { cout<<a[i]<<" "; } return 0;
}
头文件我用的是万能头文件,如果对于unique()函数而言就要用#include<algorithm>;