通过范围键保存值的结构
我需要一个结构来保存基于具有范围的键的值。 我的实现是 C++,所以任何 STL 或 Boost 都会很棒。
我有范围键,它们是双精度数,值是
- [0,2) -> 值1
- [2,5) -> 值2
- [5,10) -> value3
- 等
搜索 1.23 应返回 value1,依此类推。
现在我正在使用包含所有三个部分(key1/key2/value)的向量,并进行自定义搜索,但感觉应该有一个更清晰的结构。
编辑:谢谢大家。 鉴于本例中的范围应该是连续且不重叠的,因此使用 upper_bound 就可以正常工作。 也感谢您提供 Range 类解决方案,它们已归档以供将来参考。
I need a structure to hold a value based on a key that has a range.
My implementation is C++, so any STL or Boost would be excellent.
I have as range-key, which are doubles, and value
- [0,2) -> value1
- [2,5) -> value2
- [5,10) -> value3
- etc
Such that a search of 1.23 should return value1, and so on.
Right now I am using a vector containing all three parts, key1/key2/value, with custom searching, but it feels like there should be a cleaner structure.
Edit: Thanks all. Given the ranges in this case are supposed to be contiguous and non-overlapping, the use of upper_bound will work just fine. Thanks for the class Range solutions as well, they are filed away for future reference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的范围是连续且不重叠的,则应使用 std::map 和 upper_bound 成员函数。 或者,您可以使用带有 upper_bound 算法的排序向量。 无论哪种方式,您只需要记录范围的最低值,范围的上部由下一个较高值定义。
编辑:我的措辞令人困惑,所以我决定提供一个例子。 在编写示例时,我意识到您需要 upper_bound 而不是 lower_bound。 我总是把这两个人搞混了。
If your ranges are contiguous and non-overlapping, you should use std::map and the upper_bound member function. Or, you could use a sorted vector with the upper_bound algorithm. Either way, you only need to record the lowest value of the range, with the upper part of the range being defined by the next higher value.
Edit: I phrased that confusingly, so I decided to provide an example. In coding the example, I realized you need upper_bound instead of lower_bound. I always get those two confused.
沿着这些思路怎么样:
...程序输出:
How about something along these lines:
... program output: