简体   繁体   English

multimap upper_bound返回混淆

[英]multimap upper_bound return confusion

I have a multimap filled with pairings. 我有一个填充配对的多图。 I want to iterate through a range. 我想迭代一个范围。 upper_bound does not return an iterator pointing to an element unless it find the first element whose key is greater than the value passed to upper_bound. upper_bound不返回指向元素的迭代器,除非它找到第一个元素,其键大于传递给upper_bound的值。

How can I tell if there was no value returned from upper_bound because there's nothing greater than the passed value? 如何判断upper_bound是否没有返回值,因为没有任何值超过传递的值?

Thanks! 谢谢!

See reference and msdn 参见参考msdn

upper_bound returns the first element that is greater than your key value, if there is no element then it will return the same as end() upper_bound返回大于键值的第一个元素,如果没有元素,则返回与end()相同的元素

So you can just compare this against the end of your multimap 因此,您可以将其与多图的结尾进行比较

auto it = my_multi_map.upper_bound(some_val);
if (it == my_multi_map.end())
{
  // iterator is pointing past end so no value found
}

At least if memory serves, if upper_bound doesn't find an element with a key larger than what you passed it, it'll return container.end() . 至少如果内存服务,如果upper_bound没有找到一个键大于你传递的键的元素,它将返回container.end() This is fine for iterating with, as the norm for a pair of iterators is the beginning and one past the end of the range, so you can use container.end() as the end of a range without any problems. 这对于迭代是很好的,因为一对迭代器的范数是范围的开始和一个结束,所以你可以使用container.end()作为范围的结尾而没有任何问题。

upper_bound is actually perfect for iterating, because it points to the element just after the end of the range - just like end does. upper_bound实际上非常适合迭代,因为它指向范围结束后的元素 - 就像end一样。 So you form your loop similarly. 所以你形成你的循环类似。

for (auto it = mymap.lower_bound(start_key), end = mymap.upper_bound(end_key); it != end; ++it)

If you only want a single key, pass the same value to lower_bound and upper_bound , or use equal_range to get both at once. 如果您只需要一个键,则将相同的值传递给lower_boundupper_bound ,或使用equal_range同时获取两个键。 If the value doesn't exist in the map at all, lower_bound and upper_bound will be equal and the loop won't execute. 如果该值根本不存在于map中,则lower_boundupper_bound将相等,并且循环将不会执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM