簡體   English   中英

執行upper_bound的反轉需要做哪些更改?

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

我覺得 C++ stl 中的lower_bound不是upper_bound函數的對立面。 默認情況下,在非遞減數組中,如果我使用upper_bound並且如果找到該元素並且它不是排序數組中的最后一個元素,則給出下一個元素 > 傳遞的元素,如果該元素是最后一個元素或未找到,則返回end()迭代器。 以下 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

但現在我需要相反的東西。 我需要返回匹配元素中較小的元素。 在上面的例子中,如果我通過301 ,那么,我想得到-550作為回報。 目前,我正在使用以下代碼,它似乎適用於給定的示例,但我不確定它是否是正確的代碼,或者我需要使用二進制搜索手動實現它。

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

附注。 (p != arr.rend ())使用 if (p != arr.rend ())

std::lower_bound就是你想要的。 lower_bound返回等於或大於提供的輸入的第一個元素。 知道這一點,如果你這樣做

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

然后p將在301 ,從中減去1將為您提供元素-550 所以,你只需要在做減法之前檢查p != arr.begin() 如果是,那么減法將起作用。 如果不是,則沒有元素小於傳遞給lower_bound的輸入。 這給了你類似的東西

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