c++ 中下界的优化表示法?
auto it = v.lower_bound(val);
auto it=lower_bound(v.begin(),v.end(),val);
问题:有时,当我们使用上面给出的第一个表示法时,效果更佳,而第二个表示法则给出 Time Limit Exceed .. 。为什么????
auto it = v.lower_bound(val);
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????
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在C++标准库中,许多算法作为免费函数提供。但有时,容器可能具有同名的方法。在这种情况下,成员变体确实是优化变体。但这有一个警告:它针对该容器进行了优化。
一个例子是
std::sort
与std::list::sort
。您甚至无法使用std::sort
对列表进行排序,因为它太慢了。 “最优化”的选择是std::sort
和std::vector
。std::vector::sort
不需要特殊的优化;免费功能已经足够快了。lower_bound
类似;它也作为一些容器的自由函数和方法而存在。当您的容器已修复并且该容器具有lower_bound
方法时,请使用该方法。但是,如果您可以选择容器,则需要考虑该容器上所需的所有操作。“超出时间限制”表明竞争性编程,您需要了解大 O 的复杂性。 C++ 记录了几乎所有标准库函数的情况。
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
versusstd::list::sort
. You can't even sort lists withstd::sort
, as it would be too slow. The "most optimized" choice isstd::sort
withstd::vector
. There's no special optimization needed forstd::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 alower_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.
人们普遍误解这两个函数以相同的方式实现。
C++ 标准对此有明确规定 - 对于非 LegacyRandomAccessIterators,比较次数是线性的!
std::set
属于该类别,但将有专门针对它的更优化的lower_bound
版本。一个好的经验法则:如果可以的话,总是使用 case
v.lower_bound(val);
。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 oflower_bound
specifically for it.A good rule of thumb: always use case
v.lower_bound(val);
if you can.