从容器类中查找小于或大于范围的值

发布于 2024-10-02 11:13:49 字数 312 浏览 0 评论 0原文

目前,我有一个 std::map表,我正在寻找与特定范围匹配的键值。

例如:

从map中查找一个键值,其值应小于<< 50或大于> 50 来自搜索到的键值。

如果搜索的键值是 20 那么我想要一个来自映射范围的键值,即

-70.............20............+70

除了使用两个循环(第一个用于小于,第二个用于大于)之外,是否有更好的方法来查找键值或使用适当的方法来查找键值存储表数据用于此类操作?

Currently, I have a std::map <DWORD, DWORD> table and I'm looking for a key value matching a specific range.

For example:

Find a key value from map whose value should be either less than < 50 or greater than > 50 from the searched key value.

If the searched key value was 20 then I would want a key value of range from map i.e

-70.............20............+70

is there a better way to find a key value other than using two loop (first for less than, second for greater than) or an appropriate way to store table data for such operation?

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

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

发布评论

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

评论(1

灼痛 2024-10-09 11:13:49

如果您预先知道中间值,则可以使用 map::lower_boundmap::upper_bound 来实现此目的。

map<int, MyClass>::const_iterator lower = 
    myMap.lower_bound(-30);   // or -70 if you prefer
map<int, MyClass>::const_iterator upper = myMap.lower_bound(70);

在取消引用之前,需要检查两个迭代器的 myMap.end()

此代码片段依赖于您的排序是通常的升序 - 自定义排序可以颠倒此顺序,以便 -ve 数字出现在 +ve 之后。没有更好的方法来做到这一点 - 通过将 map 构造为二叉树,这将是高效的。

另请参阅 lower_bound 的在线示例upper_bound

请注意,DWORD 是无符号的,因此在映射中使用负数可能会给您带来警告错误,并且 -70 意外地 > 70.

You can use map::lower_bound and map::upper_bound for this, if you know the midrange value upfront.

map<int, MyClass>::const_iterator lower = 
    myMap.lower_bound(-30);   // or -70 if you prefer
map<int, MyClass>::const_iterator upper = myMap.lower_bound(70);

Both iterators need to be checked for myMap.end() before you dereference.

This snippet relies on your ordering being the usual ascending order - custom ordering could reverse this so that -ve numbers appears after +ve. There is no better way to do this - by construction of the map as a binary tree, this will be efficient.

See also online samples for lower_bound and upper_bound.

Note that DWORD is unsigned, so use of negative numbers in your map may give you a warning error, and -70 being unexpectedly > 70.

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