C++ lower_bound 與 upper_bound 函數


頭文件: #include<algorithm>

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

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

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

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

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

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

注意:如果所有元素都小於val,則返回last的位置,且last的位置是越界的!!

2 函數upper_bound()

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

注意:返回查找元素的最后一個可安插位置,也就是“元素值>查找值”的第一個元素的位置。同樣,如果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");
}

屏幕輸出:

img

參考:

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

拓展

c++ 結構體和vector進行lower_bound和upper_bound


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM