在algorithm中的二分查詢
阿新 • • 發佈:2018-11-01
首先寫algorithm 的標頭檔案
lower_bound
upper_bound
binary_search
從小到大
函式lower_bound()在first和last中的前閉後開區間進行二分查詢,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置,且last的位置是越界的
返回查詢元素的第一個可安插位置,也就是“元素值>=查詢值”的第一個元素的位置
binary_search具體
http://www.cplusplus.com/reference/algorithm/binary_search/
#include <iostream> #include <algorithm>//函式所在標頭檔案 using namespace std; int a[]={1,2,2,2,2,4,7}; int main(int argc, char *argv[]) { int p; p=lower_bound(a,a+7,2)-a;//在0到7中找第一個大於或等於2的數; cout<<p<<endl;//1 p=lower_bound(a,a+7,3)-a;//在0到7中找第一個大於或等於3的數; cout<<p<<endl;//5 p=upper_bound(a,a+7,2)-a;//在0到7中找第一個大於2的數; cout<<p<<endl;//5 return 0; }