C++ lower_bound 與 upper_bound 函數

頭文件: #include  <algorithm>html

 

二分查找的函數有 3 個: 參考:C++ lower_bound 和upper_bound數組

lower_bound(起始地址,結束地址,要查找的數值) 返回的是數值 第一個 出現的位置。函數

upper_bound(起始地址,結束地址,要查找的數值) 返回的是數值 最後一個 出現的位置。ui

binary_search(起始地址,結束地址,要查找的數值)  返回的是是否存在這麼一個數,是一個bool值url

 

 

1  函數lower_bound()  參考:有關lower_bound()函數的使用spa

 

功能:函數lower_bound()在first和last中的前閉後開區間進行二分查找,返回大於或等於val的第一個元素位置。若是全部元素都小於val,則返回last的位置..net

注意:若是全部元素都小於val,則返回last的位置,且last的位置是越界的!!code

 

2 函數upper_bound()htm

 

功能:函數upper_bound()返回的在前閉後開區間查找的關鍵字的上界,返回大於val的第一個元素位置blog

注意:返回查找元素的最後一個可安插位置,也就是「元素值>查找值」的第一個元素的位置。一樣,若是val大於數組中所有元素,返回的是last。(注意:數組下標越界)

 

PS

        lower_bound(val):返回容器中第一個值【大於或等於】val的元素的iterator位置。

        upper_bound(val): 返回容器中第一個值【大於】

 

例子:

void main() { vector<int> t; t.push_back(1); t.push_back(2); t.push_back(3); t.push_back(4); t.push_back(6); t.push_back(7); t.push_back(8); int low=lower_bound(t.begin(),t.end(),5)-t.begin(); int upp=upper_bound(t.begin(),t.end(),5)-t.begin(); cout<<low<<endl; cout<<upp<<endl; system("pause"); }

 

屏幕輸出:

 

 

參考:

STL之std::set、std::map的lower_bound和upper_bound函數使用說明

https://blog.csdn.net/jadeyansir/article/details/77015626  能夠多看幾遍

https://blog.csdn.net/tjpuacm/article/details/26389441

https://blog.csdn.net/lanzhihui_10086/article/details/43269511  

相關文章
相關標籤/搜索