如何返回严格小于 std::multimap 中给定键的最大键?
multimap
提供了lower_bound
和upper_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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AFAIK,lower/upper_bound 会将迭代器返回到该值的第一个元素,因此您可以减少它
AFAIK, lower/upper_bound will return iterator to FIRST element of this value, So you can decrease it
lower_bound
指向大于或等于参数(或end
)的最小元素。因此,将其递减一次即可得到所需的元素(如果存在)。lower_bound
points to the smallest element greater than or equal to the argument (orend
). Thus decrementing it once gives you the desired element (if it exists).