简体   繁体   English

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

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

I read the description for C++ upper_bound() function and lower_bound() function. 我阅读了C ++ upper_bound()函数和lower_bound()函数的说明。 It is interesting for me that upper_bound() only returns the first iterator with value > val (or return last iterator in the range [first, last) if val not found). 对我来说有趣的是,upper_bound()仅返回值> val的第一个迭代器(如果找不到val,则返回范围[first,last)的最后一个迭代器)。

The implementation is different from lower_bound(), while it returns the first iterator NOT SMALLER than val, so it allows the return pointer equivalent to val. 该实现与lower_bound()不同,尽管它返回的第一个迭代器NOT SMALLER而不是val,所以它允许返回指针等于val。

I am just curious to know what is the purpose to design upper_bound() in this way that upper_bound() must NOT return an iterator with value equivalent to val? 我只是很好奇地知道以这种方式设计upper_bound()的目的是什么,upper_bound()一定不能返回值等于val的迭代器?

For example: 例如:

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/ http://www.cplusplus.com/reference/algorithm/lower_bound/

In C++, iterators usually work in pairs. 在C ++中,迭代器通常成对工作。 The first iterator points to the first element to consider, and the last iterator points to one-past-the-last element to consider. 第一个迭代器指向要考虑的第一个元素,最后一个迭代器指向要考虑的倒数第二个元素。 This is to make looping easy: 这是为了使循环变得容易:

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

As such, lower_bound and upper bound together, form a "range of all elements equal to the item you searched for. The same range that std::equal_range returns. 这样, lower_boundupper bound在一起,形成一个“等于您搜索的项的所有元素的范围内。在相同范围std::equal_range回报。

upper_bound is useful in cases like std::multimap where values are stored in sorted order. upper_bound在诸如std::multimap情况下很有用,在这种情况下,值按排序顺序存储。 It lets you traverse within a range where starting position can be decided by lower_bound , and end-before-this-position is decided by upper_bound . 它使您可以在可以由lower_bound决定起始位置,由upper_bound决定结束于此位置的范围内移动。

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

This for loop would traverse till the point key == key_val . 这个for循环将遍历直到key == key_val

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

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