Jay Kim
Jay Kim

Reputation: 843

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.

How can I tell if there was no value returned from upper_bound because there's nothing greater than the passed value?

Thanks!

Upvotes: 1

Views: 2038

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308206

upper_bound is actually perfect for iterating, because it points to the element just after the end of the range - just like end does. 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. 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.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490138

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(). 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.

Upvotes: 1

EdChum
EdChum

Reputation: 394041

See reference and 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()

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
}

Upvotes: 1

Related Questions