【发布时间】:2016-09-30 15:36:44
【问题描述】:
我正在尝试使用 C++ 中 algorithm 库中的 lower_bound 和 upper_bound 函数来查找以下内容:
- 最大值小于或等于到数字 X。
- 最小值大于或等于到数字 X。
我写了以下代码:
#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;
}
但对于一些随机测试用例,它给了我错误的答案。
谁能在我的程序中找到不正确的代码?
【问题讨论】:
-
请提供一个输入序列,其中包含您得到的预期和实际结果。
-
如果你有一个单元素数组,只要
X不是那个元素,你就会得到“小于”的错误结果。 (调试提示:从不可能出错的小而琐碎的测试用例开始。)
标签: c++ algorithm binary-search divide-and-conquer