I have a vector
of double
s. I wish to find both:
- The minimum value in the vector that is greater than (or equal to) a value
x
. - The maximum value in the vector that is less than (or equal to) a value
x
.
E.g. If I have a vector:
std::vector<double> vec = {0, 1.0, 3.0, 4.0, 5.0};
and a value
x = 2.6;
I wish to find 1.0
and 3.0
.
What is the most efficient way of doing this?
I have something like:
double x1, x2; // But these need to be initialised!!!
double x = 2.6;
for (i = 0; i < vec.size(); ++i)
{
if (vec[i] >= x && vec[i] < x2)
x2 = vec[i];
if (vec[i] <= x && vec[i] > x1)
x1 = vec[i];
}
But how can I initialise x1 and x2? I could make x2 the maximum of the vector and x1 the minimum, but this requires an initial pass through the data. Is there any way to do this more efficiently?
EDIT:
A couple of assumptions I think I can/cannot make about the data:
- There are no negatives (i.e. the minimum possible number would be
0
) - It is not necessarily sorted.
std::lower_bound
to find one of the indices and find the other one in constant time from that. – Hole