C++ - 如何知道map::upper_bound()是否没有返回值?
我有一个非常简单的地图:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++ 中的大多数迭代器将被设置到集合的末尾以表示不存在的值。 这是迭代器表示“没有更多数据”的唯一有效值。
因此,您可以将
iter
与distances.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
withdistances.end()
, and if they are equal, then you've got your answer.它是
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.