頭文件:algorithm
lower_bound()返回值是一個迭代器,返回指向大於等於key的第一個值的位置
對象:有序數組或容器
數組中使用:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a[]={1,2,3,4,5,7,8,9};
printf("%d",lower_bound(a,a+8,6)-a);
return 0;
}
輸出5
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a[]={1,2,3,4,5,7,8,9};
printf("%d",lower_bound(a,a+8,0)-a);
return 0;
}
輸出0
將key換成10,所有val都小於key,返回last的位置
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a[]={1,2,3,4,5,7,8,9};
printf("%d",lower_bound(a,a+8,10)-a);
return 0;
}
輸出8
容器中使用:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> A;
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(4);
A.push_back(5);
A.push_back(7);
A.push_back(8);
A.push_back(9);
int pos = lower_bound(A.begin() , A.end() , 6)-A.begin();
cout << pos << endl;
return 0;
}
輸出5
注意:
lower_bound()函數是upper_bound()函數,它返回大於等於key的最後一個元素
也同樣是要求有序數組,若數組中無重複元素,則兩者返回值相同