繁体   English   中英

为什么C ++ lower_bound()允许返回等于val的指针,而upper_bound()不允许

[英]why C++ lower_bound() allows return pointer equivalent to val while upper_bound() does not

我阅读了C ++ upper_bound()函数和lower_bound()函数的说明。 对我来说有趣的是,upper_bound()仅返回值> val的第一个迭代器(如果找不到val,则返回范围[first,last)的最后一个迭代器)。

该实现与lower_bound()不同,尽管它返回的第一个迭代器NOT SMALLER而不是val,所以它允许返回指针等于val。

我只是很好奇地知道以这种方式设计upper_bound()的目的是什么,upper_bound()一定不能返回值等于val的迭代器?

例如:

vector<int> a = {1, 2, 3, 4};
auto i = lower_bound(a.begin(), a.end(), 2); // i is iterator at 2;
auto j = upper_bound(a.begin(), a.end(), 2); // j is iterator at 3;

http://www.cplusplus.com/reference/algorithm/lower_bound/

在C ++中,迭代器通常成对工作。 第一个迭代器指向要考虑的第一个元素,最后一个迭代器指向要考虑的倒数第二个元素。 这是为了使循环变得容易:

for(it cur=first; cur!=last; cur++)

这样, lower_boundupper bound在一起,形成一个“等于您搜索的项的所有元素的范围内。在相同范围std::equal_range回报。

upper_bound在诸如std::multimap情况下很有用,在这种情况下,值按排序顺序存储。 它使您可以在可以由lower_bound决定起始位置,由upper_bound决定结束于此位置的范围内移动。

for (iter_type it = myMap.lower_bound("key_val"); it != myMap.upper_bound("key_val"); it++)

这个for循环将遍历直到key == key_val

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM