lower_bound, upper_bound

lower_bound 返回大于等于

upper_bound 返回大于

----------------------

综合一下(按照默认集合升序排序的情况下),lower_bound、upper_bound函数不管在什么情况下,以下条件均成立。

Iterator(val) ≤ Iterator(lower_bound)≤Iterator(upper_bound)

也就是lower_bound、upper_bound构成的上下限的区间总是表示一个有效的迭代器区间(equal_range返回值),该迭代区间的长度表示关键字val在集合中出现的次数

如果二者返回值相等,表示关键字val在集合中未出现。(例外情况,集合中的所有元素均≥关键字val,返回集合的iterator::end)

如果迭代器区间长度是1,表示关键字val在集合中仅出现1次。

迭代器区间长度大于1,则表示关键字val出现多次,并且一定不是set和map这种关键字唯一的集合。

 ----------------------

 

lower_bound:

Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.

 

upper_bound:

Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.

 

int main(int argc, const char * argv[]) {
    int myints[] = {10,20,30,30,20,10,10,20};
    vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20
    
    sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30
    
    vector<int>::iterator low1,low2, up1, up2, up3;
    low1 = lower_bound (v.begin(), v.end(), 15); //^
    low2 = lower_bound (v.begin(), v.end(), 20); //^
    up1 = lower_bound (v.begin(), v.end(), 20); //^
    up2 = upper_bound (v.begin(), v.end(), 25); //
    up3 = upper_bound (v.begin(), v.end(), 100); //  =v.end()
    
    std::cout << "lower_bound for 15 is " << (low1- v.begin()) << '\n';
    std::cout << "lower_bound for 20 is " << (low2 - v.begin()) << '\n';
    std::cout << "upper_bound for 20 is " << (up1- v.begin()) << '\n';
    std::cout << "upper_bound for 25 is " << (up2 - v.begin()) << '\n';
    std::cout << "upper_bound for 100 is " << (up3 - v.begin()) << '\n';
    
    return 0;
}

 

Output:

lower_bound for 15 is 3

lower_bound for 20 is 3

upper_bound for 20 is 3

upper_bound for 25 is 6

upper_bound for 100 is 8

转载于:https://www.cnblogs.com/XingyingLiu/p/5135054.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值