如何返回严格小于 std::multimap 中给定键的最大键?

发布于 2024-11-09 18:14:27 字数 691 浏览 0 评论 0原文

multimap 提供了lower_boundupper_bound 方法。两者都可能返回一个迭代器,该迭代器的键值大于所需值,而 lower_bound 可能恰好产生所需值。

现在我想要一个值的迭代器,其中键严格小于所请求的值。如果它是 map 而不是 multimap,则实现起来相对简单,如下所述: 返回严格小于的最大密钥比 C++ 映射中的给定键。 但在 multimap 中,递减迭代器并不能保证使其指向严格较小的键。所以我需要反复递减,直到找到更小的密钥。不是特别好。

有没有更优雅的方法来做到这一点?

键通常是浮点型的。


My apologies, it turns out that you can actually do it with a single decrement. I just placed it wrong in my program, that was the real error.

multimap offers the methods lower_bound and upper_bound. Both may return an iterator to a value with key greater than the desired, with lower_bound possibly yielding exactly the desired.

Now I want an iterator to a value where the key is strictly less the requested. If it were a map rather than multimap, this would be relatively simple to achieve as described here:
Returning the greatest key strictly less than the given key in a C++ Map.
But in a multimap, decrementing an iterator is not guaranteed to make it point to a strictly smaller key. So I would need to decrement repeatedly, until a smaller key is found. Not particularly nice.

Is there a more elegant way of doing this?

The keys will in general be floating-point.


My apologies, it turns out that you can actually do it with a single decrement. I just placed it wrong in my program, that was the real error.

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

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

发布评论

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

评论(2

南汐寒笙箫 2024-11-16 18:14:27

AFAIK,lower/upper_bound 会将迭代器返回到该值的第一个元素,因此您可以减少它

AFAIK, lower/upper_bound will return iterator to FIRST element of this value, So you can decrease it

和我恋爱吧 2024-11-16 18:14:27

lower_bound 指向大于或等于参数(或end)的最小元素。因此,将其递减一次即可得到所需的元素(如果存在)。

lower_bound points to the smallest element greater than or equal to the argument (or end). Thus decrementing it once gives you the desired element (if it exists).

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