I am trying to use lower_bound
and upper_bound
functions from the algorithm
library in C++ to find the following things:
- The largest value smaller than or equal to a number X.
- The smallest value greater than or equal to a number X.
I wrote the following code:
#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;
}
But for some random test cases it gives me wrong answer.
Can anyone find the incorrect piece of code in my program?