unique函数,获得相邻序列不重复的个数。

本文介绍了C++标准库中的unique函数用于去除相邻重复元素,并通过示例展示了其使用方法。此外,还详细解释了lower_bound函数的用途及工作原理,包括如何在有序数组中查找指定值的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unique函数存在于#include <iostream>头文件中。

作用是求出相邻不重复序列的个数。此函数的返回值是首地址。

函数格式m=unique(a,a+n)-a; 

比如a[5]={1,2,2,3,2},则输出m为4.

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <list>
#include <vector>
using namespace std;
//define DEBUG
int a[1000];
int main()
{
#ifdef DEBUG
	freopen("cin.txt", "r", stdin);
	freopen("cout.txt", "w", stdout);
#endif
	int n,i,m;
	while (~scanf("%d",&n))
	{
		memset(a,0,sizeof(a));
		for (i=0;i<n;i++)
			scanf("%d",&a[i]);
		m=unique(a,a+n)-a;
		printf("%d\n",m);
	}
	return 0;
}

函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

举例如下:

一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。

所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
	int n;
	const int size=5;
	typedef vector <int> v;
	v a(size);
	a[0]=1;
	a[1]=3;
	a[2]=4;
	a[3]=6;
	a[4]=8;
	v::iterator it;
	for (it=a.begin();it!=a.end();it++)
		cout<<*it<<" ";
	cout<<endl;
	while (~scanf("%d",&n))
	{
		int k=lower_bound(a.begin(),a.end(),n)-a.begin();
		cout<<k<<endl;
	}
	return 0;
}
先用unique去重复,然后再进行排序查询。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
	int n; 
	int a[10]={1,2,2,3,5,5,7,7,8,9};
	int h=unique(a,a+10)-a;
	for (int i=0;i<h;i++)
		printf("%d ",a[i]);
	while(~scanf("%d",&n))
	{
		int k=lower_bound(a,a+h,n)-a;
		cout<<k<<endl;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值