c++ 中下界的优化表示法?

发布于 2025-01-14 04:15:07 字数 222 浏览 3 评论 0原文

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

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

问题:有时,当我们使用上面给出的第一个表示法时,效果更佳,而第二个表示法则给出 Time Limit Exceed .. 。为什么????

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森末i 2025-01-21 04:15:08

在C++标准库中,许多算法作为免费函数提供。但有时,容器可能具有同名的方法。在这种情况下,成员变体确实是优化变体。但这有一个警告:它针对该容器进行了优化。

一个例子是 std::sortstd::list::sort。您甚至无法使用 std::sort 对列表进行排序,因为它太慢了。 “最优化”的选择是 std::sortstd::vectorstd::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 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.

不再让梦枯萎 2025-01-21 04:15:07

人们普遍误解这两个函数以相同的方式实现。

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 of lower_bound specifically for it.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文