这次内容要讲到的是四个函数的使用,这些函数起到的是排序与查找的作用,这四个函数分别是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表示要查找的数字
返回值:返回数组中第一个大于某数的位置,注意是位置,要想求出下标,还需减去原数组的头坐标。
#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;
}
输出结果: