gpt4 book ai didi

c++ - 上限/下限不按我的预期工作,不明白为什么

转载 作者:太空狗 更新时间:2023-10-29 23:34:59 27 4
gpt4 key购买 nike

这是代码。结果我得到“4 4”。不明白为什么不是“2 4”(根据下限和上限的定义)。

#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 :

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

第一个元素(从 vector 的开头)不小于 34 因此 lower_bound 返回 4

来自 std::upper_bound :

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

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

造成这种混淆的原因是因为 upper_bound 返回大于给定值的第一个元素,所以根据对称性我们期望 lower_bound 返回最后一个元素(从 vector 的开头)小于给定值。但是,std 函数并不遵循这种“预期”的对称性。

关于c++ - 上限/下限不按我的预期工作,不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51954487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com