简体   繁体   中英

optimized Notaion of lower bound in c++?

  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????

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM