對C++ STL 中 lower_bound() upper_bound() 的理解


C++STL的set和multiset容器中自帶lower_bound()函數和upper_bound() 函數,當然這兩個函數也可以用於其他容器,比如array、vector等。

在使用時在思想上是一致的,但是用法上略有不同。我用vector和multiset這兩個容器舉例說明。

一、vector

 

lower_bound()函數  返回的是第一個不小於給定元素key的 位置

upper_bound() 函數  返回的是第一個大於給定元素key的  位置

用法:

 

#include<bits/stdc++.h>
using namespace std;

int main()
{
    vector<int>v;

    v.push_back(1);
    v.push_back(2);
    v.push_back(2);
    v.push_back(3);
    v.push_back(3);
    v.push_back(40);
    v.push_back(0);
    v.push_back(99);
    v.push_back(100);
    vector<int>::iterator it;

    for(it = v.begin() ; it != v.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout<<"\n----------\n";

    sort(v.begin(),v.end());

    for(it = v.begin() ; it != v.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout<<"\n----------\n";

    // lower_bound()和upper_bound()的用法,必須在有序的情況下:
  // 注意下標是從 0 開始的
vector<int>::iterator lower,upper;
lower
= lower_bound(v.begin(),v.end(),2); upper = upper_bound(v.begin(),v.end(),3); cout << "第一個不小於2的元素所在的位置的下標 " << (lower- v.begin()) << "\n"; cout << "第一個大於元素3所在的位置的下標 " << (upper - v.begin()) << "\n" ; return 0; }

 

 

二、multiset

 

lower_bound()函數  返回的是第一個不小於給定元素key的

upper_bound() 函數  返回的是第一個大於給定元素key的 

用法:

 

#include <iostream>
#include <set>
using namespace std;
int main ()
{
  multiset<int> mymultiset;
  multiset<int>::iterator itlow,itup;

  //用法:同樣必須是在有序的情況下才可以
  for (int i=1; i<8; i++) mymultiset.insert(i*10); // 10 20 30 40 50 60 70
  itlow = mymultiset.lower_bound (30);             //       ^               所求的位置上的值
  itup = mymultiset.upper_bound (40);              //             ^         所求的位置上的值

  mymultiset.erase(itlow,itup);                    //將30到50前的區間元素刪除,剩余 10 20 50 60 70

  cout<<*itlow<<endl;
  cout<<*itup<<endl;

  cout << "mymultiset contains:";

  for (multiset<int>::iterator it=mymultiset.begin(); it!=mymultiset.end(); ++it)
    cout << ' ' << *it;
    cout <<"\n";

  return 0;
}

 

參考資源;

http://www.cplusplus.com


免責聲明!

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



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