C++ lower_bound 與 upper——bound 函數

來源:互聯網
上載者:User

標籤:ast   com   url   use   nbsp   pause   net   注意   img   

標頭檔: #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");}

 

螢幕輸出:

 

 

參考:

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

77015626  可以多看幾遍

26389441

43269511  

C++ lower_bound 與 upper——bound 函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.