简体   繁体   English

执行upper_bound的反转需要做哪些更改?

[英]What is the change I need to make to perform reverse of upper_bound?

I feel lower_bound in c++ stl is not the opposite of the upper_bound function.我觉得 C++ stl 中的lower_bound不是upper_bound函数的对立面。 By default, in a non-decreasing array, if I use upper_bound and if the element is found and it is not the last element in the sorted array, then the next element > passed element is given and if the element is then last element or not found, then end() iterator returned.默认情况下,在非递减数组中,如果我使用upper_bound并且如果找到该元素并且它不是排序数组中的最后一个元素,则给出下一个元素 > 传递的元素,如果该元素是最后一个元素或未找到,则返回end()迭代器。 The following C++ code can be used to test this.以下 C++ 代码可用于对此进行测试。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int
main ()
{
  vector<int> arr{-973, -808, -550, 301, 414, 897};
  auto p = upper_bound (arr.begin (), arr.end (), 301);
  if (p != arr.end ())
    cout << *p << endl;
  else
    cout << "end" << endl;
  return 0;
}
// Output: 414

But now I need the opposite thing.但现在我需要相反的东西。 I need the smaller element from the matched element to be returned.我需要返回匹配元素中较小的元素。 In the above example, if I pass 301 , then, I want to get -550 in return.在上面的例子中,如果我通过301 ,那么,我想得到-550作为回报。 Currently, I am using the following code and it seems to work for the given example but I am not sure if it is the right code or I need to implement it manually using binary search.目前,我正在使用以下代码,它似乎适用于给定的示例,但我不确定它是否是正确的代码,或者我需要使用二进制搜索手动实现它。

auto p = upper_bound(arr.rbegin(), arr.rend(), 301, greater<int>());

PS.附注。 I am using if (p != arr.rend ()) for this.(p != arr.rend ())使用 if (p != arr.rend ())

std::lower_bound is what you want here. std::lower_bound就是你想要的。 lower_bound returns the first element that is equal to or greater than the input provided. lower_bound返回等于或大于提供的输入的第一个元素。 Knowing that, if you do知道这一点,如果你这样做

auto p = lower_bound(arr.begin (), arr.end (), 301);

then p will be at the 301 , and subtracting 1 from it will give you element -550 .然后p将在301 ,从中减去1将为您提供元素-550 So, you just need to check before you do that subtraction that p != arr.begin() .所以,你只需要在做减法之前检查p != arr.begin() If it is, then the subtraction will work.如果是,那么减法将起作用。 If it isn't, then there is no element less then the input passed to lower_bound .如果不是,则没有元素小于传递给lower_bound的输入。 That gives you something like这给了你类似的东西

auto p = lower_bound(arr.begin (), arr.end (), input_value);
if (p == arr.begin())
    std::cout << "no element found less than " << input_value;
else
    std::cout << "first element less than " << input_value << " is " << *std::prev(p);

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

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