STL 中的上界和下界搜索算法

原文:https://www.studytonight.com/cpp/stl/stl-searching-lower-upper-bound

upper_bound()返回给定范围内元素的迭代器,该迭代器的比较结果不大于给定值。给定的范围应该已经排序,以便 upper_bound()正常工作。换句话说,它返回给定排序范围内给定元素上限的迭代器。

#include <iostream>    
#include <algorithm> 
#include <vector>
using namespace std;

int main ()
{
    int input[] = {1,2,2,3,4,4,5,6,7,8,10,45};
    vector<int> v(input, input+12);

    vector<int>::iterator it1 , it2;

    it1 = **upper_bound**(v.begin(), v.end(), 6); 
    */* points to eight element in v */* 

    it2 = **upper_bound**(v.begin(), v.end(), 4);
    */* points to seventh element in v */*
}

lower_bound方法

lower_bound()返回给定范围内元素的迭代器,该迭代器不小于给定值。给定的范围应该已经排序,以便 lower_bound()正常工作。换句话说,它返回给定排序范围内给定元素下限的迭代器。

#include <iostream>     
#include <algorithm>   
#include <vector>
using namespace std;

int main ()
{
    int input[] = {1,2,2,3,4,4,5,6,7,8,10,45};
    vector<int> **v**(input,input+12);

    vector<int>::iterator it1 , it2;

    it1 = **lower_bound**(**v**.begin(), **v**.end(), 4); 
    */* points to fifth element in v */* 

    it2 = **lower_bound** (**v**.begin(), **v**.end(), 10);
    */* points to second last element in v */*
}