本文介绍了上下限不符合我的预期,无法理解为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码.结果,我得到"4 4".不明白为什么它不是"2 4"(根据上下限的定义).

Here is the code. As a result I get "4 4". Don't understand why it is not "2 4" (according to lower and upper bounds' defenitions).

#include <bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> v = {1, 2, 4, 5};
    vector<int>::iterator s , f;
    s = lower_bound(v.begin(), v.end(), 3);
    f = upper_bound(v.begin(), v.end(), 3);
    cout << (*s) << " " << (*f);
    return 0;
}

推荐答案

来自 std::lower_bound :

不小于3的第一个元素(从向量的开头)为4,因此lower_bound返回4.

The first element (from the beginning of the vector) which is not less than 3 is 4 and hence lower_bound returns 4.

来自 std::upper_bound :

(从向量的开头开始)大于3的第一个元素是4,因此upper_bound返回4.

The first element (from the beginning of the vector) which is greater than 3 is 4 and hence upper_bound returns 4.

造成这种混乱的原因是,由于upper_bound返回的第一个元素大于给定值,因此,对称起见,我们期望lower_bound返回的最后一个元素(从向量的开头)小于给定值.但可惜,std函数不遵循这种预期的"对称性.

The reason for this confusion is because upper_bound returns the first element that is greater than the given value, so by symmetry we expect lower_bound to return the last element (from the beginning of the vector) that is less than the given value. But alas, the std function doesn't obey this "expected" symmetry.

这篇关于上下限不符合我的预期,无法理解为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:25