书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

lower_bound的用法

lower_bound的headfile是algorithm.

lower_bound的工作原理就是二分查找了。

 

lower_bound的作用:

lower_bound的返回值减去数组的地址就是

要查找的元素在数组中的位置。

即:Pos = lower_bound(a, a+10, 3)-a;

那么Pos就是在数组a[10]中的位置了。

 

下面给出它的具体用法并说明一些要注意的问题。

View Code
#include "iostream"
#include "algorithm"
using namespace std;

int main()
{
int a[4]={1, 2, 3, 4};
int temp1 = lower_bound(a, a+4, -11)-a;
int temp2 = lower_bound(a, a+4, 3)-a;
int temp3 = lower_bound(a, a+4, 8)-a;

int b[2][2] = {{1, 2},{3, 4}};
int temp4 = lower_bound(b[0], b[0]+2, 2) - b[0];
cout<<temp1<<" "<<temp2<<" "<<temp3<<endl;
cout<<temp4<<endl;
}

注意有两点:

第1:当key<=a[0]时, temp值为0;

第2:当key>a[col]时(col为数组的列数),temp值为col;

其它的就没什么了。

 

有了这个,以后就可以不用写while()来实现二分查找了。

posted on 2012-03-21 22:13  More study needed.  阅读(887)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!