[英]Bucket Key Value Map?
I need a structure where I can push Key Values where the Keys are ordered ascending. 我需要一个结构,我可以按键升序排序键值。 If I request a Value to a Key, I would like to get the Value of the nearest bigger (but not equal) Key inside of the Map.
如果我向一个Key请求一个Value,我想得到Map中最接近的更大(但不相等)Key的值。
So for example, I do push 100, 500 and 1000. If I request 750 I do get the 1000 Value. 因此,例如,我确实推动100,500和1000.如果我请求750,我会得到1000值。 If I request 450 I get the 500 Value.
如果我要求450,我会获得500 Value。 If I request 500, I get the 1000 value.
如果我请求500,我得到1000值。 Those keys are dynamic, a switch isn't possible here.
这些键是动态的,这里不可能切换。
My approach would be to push a Class with a key and a value to a vector but this would last in a O(n). 我的方法是将带有键和值的类推送到向量,但这将持续为O(n)。
Is there a better way/faster way to implement this instead of iterating forward through a Key vector and compare? 是否有更好的方法/更快的方法来实现它而不是通过Key向量迭代并进行比较?
I think you should use std::map
as the container. 我认为你应该使用
std::map
作为容器。 and use std::map::upper_bound
to find the nearest bigger key. 并使用
std::map::upper_bound
查找最近的较大键。
In case of equal is acceptable, use std::map::lower_bound
. 如果可以接受,则使用
std::map::lower_bound
。
std::map::upper_bound
and std::map::lower_bound
is guaranteed the complexity as O(log(n)). std::map::upper_bound
和std::map::lower_bound
保证复杂度为O(log(n))。
By the way, if you still want to use std::vector
, std::upper_bound
and std::lower_bound
is guaranteed to have complexity as O(log(n)) for std::vector
顺便说一句,如果你仍然想使用
std::vector
, std::upper_bound
和std::lower_bound
保证复杂度为std::lower_bound
(对于std::vector
)的log(n)
Use std::map
and std::map::upper_bound()
. 使用
std::map
和std::map::upper_bound()
。 std::map
is implemented as a tree, so std::map::upper_bound()
is guaranteed to be O(log(n)). std::map
实现为树,因此std::map::upper_bound()
保证为O(log(n))。
std::map
is sorted by the key using a given comparison function (default: std::less
). std::map
使用给定的比较函数按键排序(默认值: std::less
)。 It include should everything you need. 它应该包括你需要的一切。
you can use heap(min-heap or max-heap). 你可以使用堆(最小堆或最大堆)。 insert delete or find is O(log(n)), and easy to implement.
insert delete或find是O(log(n)),易于实现。 in fact it is similar to map, but you can code by you idea.
实际上它与地图相似,但你可以按照你的想法编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.