泛型算法(十五)之有序序列中的边界查找算法

本文详细介绍了C++ STL中的查找算法,包括equal_range、lower_bound、upper_bound等函数的应用及示例。通过具体的代码实例展示了如何在已排序序列中查找特定值的位置范围及其上下界。

1、equal_range(forIterBegin, forIterEnd, targetVal):在已排序的序列中查找目标值的位置范围;返回范围的下界与上界。对于随机迭代器,用二分查找;否则线性查找。返回pair<ForwardIterator, ForwardIterator>

    std::vector<int> c = {0, 1, 2, 2, 2, 2, 4};
    //查找序列中值为2的元素的位置范围
    auto p = std::equal_range(c.begin(), c.end(), 2);
    //输出
    std::cout <<"at positions "<< (p.first - c.begin()) << " and " << (p.second - c.begin());
    //打印结果:at positions 2 and 6

2、equal_range(forIterBegin, forIterEnd, targetVal, binPred):重载版本,其中binPred是给定的序关系函数。

自己实现binPred,向算法定制操作。

3、lower_bound(forIterBegin, forIterEnd, targetVal):在升序的序列中查找第一个不小于targetVal的元素,实际上是二分查找。

    std::vector<int> c = {0, 1, 2, 3, 5, 6};
    //查找序列中查找第一个不小于4的元素
    auto iter = std::lower_bound(c.begin(), c.end(), 4);
    //输出
    std::cout << *iter;
    //打印结果:5

4、lower_bound(forIterBegin, forIterEnd, targetVal, binPred):重载版本,其中binPred是给定的序关系函数。

自己实现binPred,向算法定制操作。

5、upper_bound(forIterBegin, forIterEnd, val):在已排序的序列中查找目标值val出现的上界(即第一个大于目标值val的元素的位置)。

    std::vector<int> c = {0, 1, 2, 3, 5, 6};
    //查找序列中查找第一个大于4的元素
    auto iter = std::upper_bound(c.begin(), c.end(), 4);
    //输出
    std::cout << *iter;
    //打印结果:5

6、upper_bound(forIterBegin, forIterEnd, val, binPred):重载版本,其中binPred是给定的序关系函数。

自己实现binPred,向算法定制操作。

转载于:https://www.cnblogs.com/dongerlei/p/5144605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值