/*****************c++ STL 里的upper_bound 和 lower_bound 的用法~~*********************/

来源:互联网 发布:淘宝精选安踏鞋 编辑:程序博客网 时间:2024/05/22 12:36

今天学习了一下STL里的upper_bound 和lower_bound的用法,简单点来说,这就是基于二分搜索的一个函数~~

写这个东西主要是给自己做STL学习笔记一用,算不上什么教程,如果看更权威一点的话 还不如找一找这里的说明http://www.cplusplus.com/reference/algorithm/upper_bound/?kw=upper_bound 这里主要结合vector容器来讲述,二话不说,直接上示例代码~

#include<iostream>#include<algorithm>#include<vector>using namespace std;int main(){    int mints[] = {10,20,30,20,10,10,20};    vector<int> v(mints,mints + 8);    sort(v.begin(),v.end());    vector<int>::iterator low,up;    low = lower_bound(v.begin(),v.end(),20);    up = upper_bound(v.begin(),v.end(),20);    //Returns an iterator pointing to the first element in the range [first,last) which compares greater than val    cout<<"lower_bound at position "<<low - v.begin()<<endl;    cout<<"upper_bound at position "<<up  - v.begin()<<endl;    cout<<"the numbers of the 20 int the array"<<up - low<<endl;    sort(mints,mints + 8);    cout<<"the sorted array,20's lower_bound at position "<<upper_bound(mints,mints + 8,20) - mints<<endl;    cout<<"the sorted array,20's lower_bound at position "<<upper_bound(mints,mints + 8,20) - mints<<endl;    cout<<"the numbers of the 20 int the array"<<upper_bound(mints,mints + 8,20) - upper_bound(mints,mints + 8,20)<<endl;    return 0;}

以下是程序的运行结果



好吧,都不知道这个算不算是技术的blog了,尼玛怎么总觉得这篇blog写得好水啊QAQ快哭了快哭了
0 0