lower_bound
will return the iterator equal to the map's end()
when the item you're searching for isn't in the map, and it's insertion point would be at the end of the map. Since end()
is one past the end of the map, it doesn't point to a valid element of the map. Trying to dereference it is an error. Be lucky that you were running this in Debug mode with a checked iterator, otherwise you'd have just gotten undefined behavior instead of a nice error message.
The reason it changes when you order the map without greater
is that it changes the order of the map; lower_bound
is now returning begin()
instead of end()
, which is a valid element.
To see whether the element was found in the map, you should use equal_range
instead of lower_bound
and check that the two iterators are not equal. The first of the two is identical to what lower_bound
returns.