STL之sort(),binary_search(),lower_bound(),upper_bound()函数

这次内容要讲到的是四个函数的使用,这些函数起到的是排序与查找的作用,这四个函数分别是sort(),binary_search(),lower_bound(),upper_bound().他们都是用在数组中的,当然vector也是可以的。

这四个函数的头文件均为:#include<algorithm>

1.sort()

函数作用:为一个数组进行排序,其时间复杂度为:n*logn

函数模板:sort(first,last,cmp)

参数说明:first表示要排序数组的首元素的地址,last表示要排序数组尾元素的地址,cmp表示排序方式,默认排序为升序排序。

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b){
	return a > b;
}
int main(){
	int num[10],i;
	for (i = 0; i < 10; i++){
		cin >> num[i];
	}
	sort(num, num + 10);
	for (i = 0; i < 10; i++){
		cout << num[i]<<" ";
	}
	cout << endl;
	sort(num, num + 10, cmp);
	for (i = 0; i < 10; i++){
		cout << num[i] << " ";
	}
	cout << endl;
}
2.binary_search()

函数作用:查找数组中是否具有某元素

函数模板:binary_search(first,last,indx)

参数说明:first表示要排序数组的首元素的地址,last表示要排序数组尾元素的地址,indx表示要查找的数字

返回值:若查找到,则返回true,查找不到,返回false

注意:在查找前,先按照升序排好序,相信二分查找的方法我就无需赘述了。

我们可以看到,binary_search()只能返回是否找到,具体在哪个位置,却无法告知,因此就出现了lower_bound(),upper_bound()两个函数。

3.lower_bound()

函数作用:查找数组中第一个大于等于某数的位置

函数模板:lower_bound(first,last,indx)

参数说明:first表示要排序数组的首元素的地址,last表示要排序数组尾元素的地址,indx表示要查找的数字

返回值:返回数组中第一个大于等于某数的位置,注意是位置,要想求出下标,还需减去原数组的头坐标。

4.upper_bound()

函数作用:查找数组中第一个大于某数的位置

函数模板:upper_bound(first,last,indx)

参数说明:first表示要排序数组的首元素的地址,last表示要排序数组尾元素的地址,indx表示要查找的数字

返回值:返回数组中第一个大于某数的位置,注意是位置,要想求出下标,还需减去原数组的头坐标。


4个函数结合运用的代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int num[10],i;
	for (i = 0; i < 10; i++){
		cin >> num[i];
	}
	sort(num, num + 10);
	for (i = 0; i < 10; i++){
		cout << num[i]<<" ";
	}
	cout << endl;
	cout << "关于8的搜索结果:";
	if (binary_search(num, num + 10, 8)){
		cout << "yes" << endl;
	}
	else{
		cout << "no" << endl;
	}
	cout << "lower_bound:" << lower_bound(num, num + 10, 8)-num<<endl;
	cout << "upper_bound:" << upper_bound(num, num + 10, 8)-num<<endl;
	cout << "关于11的搜索结果:";
	if (binary_search(num, num + 10, 11)){
		cout << "yes" << endl;
	}
	else{
		cout << "no" << endl;
	}
	cout << "lower_bound:" << lower_bound(num, num + 10, 11) - num << endl;
	cout << "upper_bound:" << upper_bound(num, num + 10, 11)-num<<endl;
}
输出结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值