【问题标题】:why C++ lower_bound() allows return pointer equivalent to val while upper_bound() does not为什么 C++ lower_bound() 允许返回与 val 等效的指针,而 upper_bound() 不允许
【发布时间】:2016-11-25 16:33:03
【问题描述】:

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

实现与lower_bound()不同,它返回的第一个迭代器NOT SMALLER than 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++ stl


    【解决方案1】:

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

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

    因此,lower_bound 和 upper bound 一起形成一个“所有元素的范围等于您搜索的项目。std::equal_range 返回的范围相同。

    【讨论】:

    • 另外,如果您将一个值插入到已排序数组的 lower_bound 或 upper_bound 位置,则该数组将保持排序状态。
    【解决方案2】:

    upper_bound 在像std::multimap 这样的值按排序顺序存储的情况下很有用。它允许您在 starting 位置可以由lower_bound 决定的范围内遍历,而 end-before-this-position 由upper_bound 决定。

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2013-05-08
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      相关资源
      最近更新 更多