Dee*_*mah 4 c++ algorithm binary-search divide-and-conquer
我正在尝试使用C++ 库中的lower_bound和upper_bound函数algorithm来查找以下内容:
我写了以下代码:
#include <iostream>
#include <algorithm>
int main() {
using namespace std;
int numElems;
cin >> numElems;
int ar[numElems];
for (int i = 0; i < numElems; ++i)
cin >> ar[i];
stable_sort(ar,ar+numElems);
cout << "Input number X to find the largest number samller than or equal to X\n";
int X;
cin >> X;
int *iter = lower_bound(ar,ar+numElems,X);
if (iter == ar+numElems)
cout << "Sorry, no such number exists\n";
else if (*iter != X && iter != ar)
cout << *(iter-1) << endl;
else
cout << *iter << endl;
cout << "Input number X to find the smallest number greater than or equal to X\n";
cin >> X;
int *iter2 = lower_bound(ar,ar+numElems,X);
if (iter2 == ar+numElems)
cout << "Sorry, no such number exists\n";
else
cout << *iter2 << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但对于一些随机测试用例,它给了我错误的答案。
谁能在我的程序中找到不正确的代码吗?
小于或等于数字 X 的最大值。
对我来说,排序数组最简单的方法是:
auto ret = upper_bound(arr.rbegin(), arr.rend(), X,
[](int a, int b){return a>=b;});
Run Code Online (Sandbox Code Playgroud)