比较函数对upper_bound和lower_bound的影响

问题描述 投票:0回答:1

我想了解比较功能(< or <=) on both

lower_bound
upper_bound
功能)的影响。

考虑这个程序:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


int main() {
        vector<int> v = {0, 1, 2, 3, 3, 3, 3, 3, 4, 5, 6, 7};

        auto it1 = lower_bound(v.begin(), v.end(), 3, [](int a, int b) {return a < b;});
        auto it2 = lower_bound(v.begin(), v.end(), 3, [](int a, int b) {return a <= b;});
        auto it3 = upper_bound(v.begin(), v.end(), 3, [](int a, int b) {return a < b;});
        auto it4 = upper_bound(v.begin(), v.end(), 3, [](int a, int b) {return a <= b;});


        cout << distance(v.begin(), it1) << endl;
        cout << distance(v.begin(), it2) << endl;
        cout << distance(v.begin(), it3) << endl;
        cout << distance(v.begin(), it4) << endl;

        return 0;
}

这个结果是:

3
8
8
3

有人能解释一下这个结果吗?

我们可以说

lower_bound
与 < is equivalent to
upper_bound
与 <= all the time?

同样的问题(

lower_bound
,<=) and (
upper_bound
,<).

c++ comparison-operators lower-bound upperbound
1个回答
0
投票

您以错误的方向改变了算法。使用 <= in the comparator is just like telling to the opposite to the

upper_/lower_bound()
。如果您在第一次迭代中手动执行算法,您将面临困境 - 您找到了 3 个,但比较器对您说 - “继续前进”。因此,您得到的结果是 3,因为比较器告诉您跳过等于目标的值。

© www.soinside.com 2019 - 2024. All rights reserved.