算法 set / multiset -- lower_bound()的二分搜索

lower_bound() 在数组中搜索时 

搜不到

返回 .end(),

若需要返回0,用upper_bound()-lower_bound()

若要返回下一个下标  则需要在set / multiset 中使用lower_bound()

下面是测试代码及样例

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<list>
#include<set>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> p;
typedef long double ld;
#define mem(x) memset(x, 0, sizeof(x))
#define me(x) memset(x, -1, sizeof(x))
#define fo(i,n) for(i=0; i<n; i++)
#define sc(x) scanf("%lf", &x)
#define pr(x) printf("%lld
", x)
#define pri(x) printf("%lld ", x)
#define lowbit(x) x&-x
const ll MOD = 1e18 +7;
const ll N = 6e6 +5;
set<ll> s;
int main()
{
    ll i, j, k, l=1;
    ll n, m, t;
    //cin>>n;
    n=10;
    for(i=0; i<n; i++)
        s.insert(i);
    set<ll>::iterator it;
    cout<<"输出set"<<endl;
    for(it=s.begin(); it!=s.end(); it++) k=*it,cout<<k<<" ";cout<<endl;
    while(cin>>k)
    {
        it=s.lower_bound(k);
        t=*it;
        //if(t==k)
        //cout<<"找到"
        cout<<t<<endl;
        if(it!=s.end())
        {
            if(t==k)
            cout<<"找到"<<t<<endl<<endl;
            else cout<<"未找到 返回下一个下标 输出*(it+1) "<<t<<endl<<endl;
            s.erase(it);
        }
        else
        {
            cout<<"返回 s.end()下标 "<<t<<endl<<endl;
        }
        for(it=s.begin(); it!=s.end(); it++) k=*it,cout<<k<<" ";cout<<endl<<endl;
    }
    return 0;
}
View Code

原文地址:https://www.cnblogs.com/op-z/p/10778422.html