STL中的二分查找函数

来源:互联网 发布:回力帆布鞋知乎 编辑:程序博客网 时间:2024/06/05 19:15


头文件 <algorithm>

查找函数可以分为两类

① count find 用于非有序序列的查找,On的复杂度。

② binary_search upper_bound  lower_bound equal_range 用于有序序列的查找,Ologn的复杂度。


① 

count(num,num+n,w);

count(v.begin(),v.end(),w);

返回值是一个数,代表从起始到结束位置数w的个数。


find(num,num+n,w);

find(v.begin(),v.end(),w);

返回值是一个指针,若找到w,则指向找到的第一个w,若找不到,则指向队尾元素的下一个位置。

可以在函数后面加-num、-v.begin() 使其返回下标。


binary_search(num,num+n,w);

binary_search(v.begin(),v.end(),w);

返回值是一个布尔类型变量,找到为true,否则为false。


lower_bound(num,num+n,w);

lower_bound(v.begin(),v.end(),w);

返回值是一个指针,指向第一个大于等于w的数。

即:若w存在,则指向第一个w,若w不存在,则指向第一个大于w的数,若所有数均小于w,则指向队尾的后一个位置。

同样可以在函数后面加-num、-v.begin() 使其返回下标。


upper_bound(num,num+n,w);

upper_bound(v.begin(),v.end(),w);

返回值是一个指针,指向第一个大于w的数。

即:不管w存在还是不存在,都指向第一个大于w的数,若全部小于w,则指向队尾的后一个位置。

同样可以在函数后面加-num、-v.begin() 使其返回下标。


equal_range (num,num+n,w);

equal_range (v.begin(),v.end(),w);

返回值是pair类型,其中第一个值是lower_bound的返回值,第二个是upper_bound的返回值
原创粉丝点击