Finding an int key less than or equal to

Oct 30, 2009 at 8:35pm
For a map of int, is it possible to use an STL algorithm to find a key that is less than or equal to a value, that itself may be absent?

If not, no need to provide code: can write the loop myself.
Oct 30, 2009 at 9:08pm
Looks like you are trying to do something slightly different from lowerbound which finds the first element greater or equal. the only algorithm that could do this would be foreach which is essentially a while loop under the covers. You'd have to define a functor with for_each that stores the iterator to the item that you are looking for and returns. I don't think that there is any algorithm that could do this logarithmically as lower_bound would.
Oct 30, 2009 at 9:18pm
Oh, wait. find_if would work as well and probably be simpler to use.
Last edited on Oct 30, 2009 at 9:22pm
Oct 30, 2009 at 9:21pm
Actually wait. Why not just use the lower_bound member function? Then you can simply backup by one after it finishes or check if it is at the beginning? I guess it depends on the complexity of the container. If it is huge, you can use lower bound and then check if the iterator needs to be backed up by one. If it is small then you might be better off with a linear find that iterates from the beginning.
Last edited on Oct 30, 2009 at 9:29pm
Nov 1, 2009 at 10:20pm
Thanks for the replies.
Topic archived. No new replies allowed.