上限/下限没有像我预期的那样工作,无法理解为什么
Upper/lower bounds don't work as I expect, can not understand why
这是代码。结果我得到"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
:
返回指向区域中第一个元素的迭代器[第一,最后(不比瓦尔少。
第一个元素(从向量的开头开始(不小于3
是4
,因此lower_bound
返回4
。
从std::upper_bound
:
返回一个迭代器,该迭代器指向区域[first,last(中的第一个元素,该元素的比较大于val。
大于3
的第一个元素(从向量的开头开始(是4
的,因此upper_bound
返回4
。
造成这种混淆的原因是upper_bound
返回大于给定值的第一个元素,因此通过对称性,我们期望lower_bound
返回小于给定值的最后一个元素(从向量的开头开始(。但遗憾的是,std
函数不服从这种"预期"的对称性。
知道std::equal_range()
返回一对迭代器会更容易理解/记住std::lower_bound()
和std::upper_bound()
返回的内容,其中第一个迭代器等于std::lower_bound()
返回的内容,第二个迭代器等于std::upper_bound()
返回的内容。
因此,以下是使用参数4
调用它们的不同情况:
1 2 3 4 4 4 4 5 E
| |
F S - first points to the first element, second to the one behind last, representing range which contains 4
1 2 3 4 5 E
| |
F S same for one element
1 2 3 4 E
| |
F S same as before, but 4 is the last element
1 2 3 5 E
|
F==S first == second, which means range for elements equal to 4 is empty
1 2 3 E
|
F==S same as before but there is no element greater than 4
其中E
表示container.end()
返回的内容 - 最后一个元素后面的迭代器。
lower_bound
和upper_bound
的命名是不幸的,因为它会引起混淆。在搜索具有多个元素的序列时,这些名称是指与您正在搜索的元素完全相同的结果;lower_bound
将迭代器返回到开始,upper_bound
返回一个超过结束的迭代器。
当元素不是序列的一部分时,它们都会将迭代器返回到第一个大于您要搜索的元素的元素。如果没有更大的迭代器,这可能是end
迭代器。
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 为什么我的 std::ref 无法按预期工作?
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 有人能解释一下为什么下界是这样工作的吗C++的
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 为什么stream::忽略未按预期工作
- 为什么 HeapFree() 不能正常工作?
- 为什么我在 AVR 中的中断无法正常工作?
- 为什么指针在对二维数组进行排序时无法正常工作?
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 为什么 sizeof(ar)/ sizeof(ar[0]) 在传递给函数时无法在向量上正常工作?
- 为什么它在不分配内存的情况下工作正常
- 为什么重载运算符"="动态数组的类上无法正常工作?C++
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- 静态 constexpr 函数在模板结构中工作,但不能在结构中工作.为什么?
- 禁用 GPU 使我的 CNTK 程序正常工作.为什么
- C++余弦在没有 std 命名空间的情况下工作 - 为什么
- c++的pow(2,1000)对于double来说通常太大了,但它正在工作.为什么
- 程序不是在win上工作,而是在mac上工作.为什么?
- 当我用字符串代替char时,代码可以完美地工作.为什么如此