Home > database >  optimized Notaion of lower bound in c ?
optimized Notaion of lower bound in c ?

Time:03-16

  1. auto it = v.lower_bound(val);

  2. auto it=lower_bound(v.begin(),v.end(),val);

Question: sometimes when we use first notation given above that's works more optimally while second one gives Time Limit Exceed ...Why????

CodePudding user response:

It's a common misconception that these two functions are implemented in the same way.

The C standard is explicit on this - for non-LegacyRandomAccessIterators, the number of comparisons is linear! std::set falls into that category, but will have a more optimised version of lower_bound specifically for it.

A good rule of thumb: always use case v.lower_bound(val); if you can.

CodePudding user response:

In the C Standard Library, many algorithms are provided as free functions. But sometimes, containers may have methods with the same name. When this is the case, the member variant is indeed the optimized variant. But that comes with a caveat: it's optimized for that container.

An example is std::sort versus std::list::sort. You can't even sort lists with std::sort, as it would be too slow. The "most optimized" choice is std::sort with std::vector. There's no special optimization needed for std::vector::sort; the free function is already fast enough.

lower_bound is similar; it too exists as a free function and a method of some containers. When your container is fixed, and that container has a lower_bound method, use that. But if you can choose your container, you need to consider all operations you need on that container.

The "Time Limit Exceeded" suggests competitive programming, where you need to know big-O complexity. C documents that for almost all Standard Library functions.

  • Related