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. 閱讀(917) 評論(0) 收藏 舉報

浙公網安備 33010602011771號