C++ - 如何知道map::upper_bound()是否没有返回值?

发布于 2024-07-20 21:47:38 字数 367 浏览 3 评论 0原文

我有一个非常简单的地图:

std::map<int, double> distances;
distances[20.5] = 1;
distances[19] = 2;
distances[24] = 3;

在这种情况下使用 map::upper_bound() 时,我如何知道是否没有任何返回值:

std::map<int, double>::iterator iter = distances.upper_bound(24);

(24 是最大键,因此返回意外结果,但如何通过代码知道这一点?如何知道我已经达到了最大键?)。

谢谢 !

I've got a very simple map :

std::map<int, double> distances;
distances[20.5] = 1;
distances[19] = 2;
distances[24] = 3;

How do i know if there isn't any returned value, when using a map::upper_bound() in this case for example:

std::map<int, double>::iterator iter = distances.upper_bound(24);

(24 is the max key so an unexpected result is returned, but how to know that through the code ? How to know i've reached the max key ?).

Thanks !

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

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

发布评论

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

评论(3

相守太难 2024-07-27 21:47:38
if (iter == distances.end())
    // no upper bound
if (iter == distances.end())
    // no upper bound
征棹 2024-07-27 21:47:38

C++ 中的大多数迭代器将被设置到集合的末尾以表示不存在的值。 这是迭代器表示“没有更多数据”的唯一有效值。

因此,您可以将 iterdistances.end() 进行比较,如果它们相等,那么您就得到了答案。

Most iterators in C++ will be set to the end of the collection to represent an absent value. This is the only valid value for an iterator to represent "no more data".

So you can compare iter with distances.end(), and if they are equal, then you've got your answer.

别念他 2024-07-27 21:47:38

它是 distances.end(),这很有意义。 直观上,upper_bound() 返回指向第一个位置的迭代器,该位置是您的键在地图中的位置“之后”。 如果映射中的所有键都小于或等于您的键,那么所有这些键“之后”的第一个位置就是结束迭代器。

It's distances.end(), which makes perfect sense. Intuitively, upper_bound() returns the iterator that points to the first place which is "after" where your key is or would be in the map. If all the keys in the map are less than or equal to your key, then the first place that is "after" all of them is the end iterator.

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