5 ms·
> You want one that doesn't require a consolation with a manual to remember if it returns the first value that's greater or the last value that's lower. ... No
by re 2y ago
> You want one that doesn't require a consolation with a manual to remember if it returns the first value that's greater or the last value that's lower. ... No more needing to remember "does this return the highest index whose value is lower than the value I'm searching for, or the lowest index whose value is greater than the value I'm searching for?". This one returns both, so you can use whichever you need for your use case.
This (italicized part) feels like a weird requirement. Function/API documentation (which this author's code lacks) is important, and I don't think I ever write a call to an unfamiliar function without checking the docs for it. Assuming that you know what a function does based on the name alone is a recipe for buggy code.
This is also a kind of unusual formulation of binary search which searches across a monotonic function space rather than a sequence. I get that this is more general and can be used to implement the latter, but a less general interface that only works on sequences is IMO more intuitive: in that case, I expect it to return either the index of the target number, or the index where it should be inserted if not found. It's somewhat telling that the author doesn't offer any code examples demonstrating how to use this wonderful general function to solve the common use case of finding an element in a sorted vector, or inserting a new one into the correct location.
- edflsafoiewq 2y agoThe interface is nicer for keyframe interpolation eg. the problem where you have a list of (X,Y) pairs and you want to find the two pairs that straddle a given x and interpolate between them. In that case, search(|&i| v[i].0 >= x, 0, v.len() - 1) handles the three cases "before the beginning", "after the end", and "between two pairs" fairly naturally.