One option is to use the std::map container with doubles as keys and values corresponding to what value is assigned to the range whose upper endpoint is the given value. For example, given your file, you will have a map like this:
std::map<double, std::string> lookup; lookup[1.0] = "A"; lookup[2.5] = "B"; lookup[7.0] = "C";
Then you can use the std::map::lower_bound specified by some point to return a key / value pair whose key (upper end point) is the first key on the map that is at least as large as the one in question point, For example, with the map above, lookup.lower_bound(1.37) will return an iterator with the value "B.", lookup.lower_bound(2.56) will return an iterator whose value is "C." These searches are quick; they take O (log n) time to display with n elements.
In the above, I assume that the values you are looking for are non-negative. If negative values are acceptable, you can add a quick test to check if the value is negative before doing any checks. This way you can eliminate the side effects.
Why is it worth it, if you know something about the distribution of your queries (for example, they are evenly distributed), you can create a special data structure called the optimal binary search tree , which will give better access time than std::map . Also, depending on your application, there may be even faster options. For example, if you do this because you want to randomly select one of the results with different probabilities, I would suggest studying this article about the alias method , which allows you to generate random values over O (1).
Hope this helps!
source share