7

I've been wondering if it's possible to iterate through part of a map, based on a starting key that may or may not exist. If I had a map with keys full of positions, I would like to say,

"return an iterator such that if _Key doesn't exist, I am returned the closest iterator before _Key"

I could use this to emplace_hint a new value, or loop through a specific range of positions even if the search key does not exist. Is this kind of functionality easily available to us in some way?

  • `map::lower_bound` ? – quantdev Aug 19 '14 at 13:37
  • possible duplicate of [Map - finding nearest value?](http://stackoverflow.com/questions/6730136/map-finding-nearest-value) – quantdev Aug 19 '14 at 13:37
  • @quantdev Similar, but I think this question and answer can prove much more relevant to the thoughts of C++ programmers starting to work with STL containers, as long as a clear answer is provided here. –  Aug 19 '14 at 13:46

1 Answers1

5

Use lower_bound and then decrease iterator, after checking it doesn't point to begin iterator, as Andre Kostur said. It returns an iterator pointing to the first element in the container whose key is not considered to go before k (i.e., either it is equivalent or goes after). Complexity O(log n).

JKS
  • 339
  • 1
  • 12
  • 3
    After checking lower_bound doesn't return the end iterator! – Neil Kirk Aug 19 '14 at 13:37
  • Wonderful! I was blissfully unaware of the function of lower_bound. Would it be possible to have a summary of its functionality for when I'm allowed to accept an answer? –  Aug 19 '14 at 13:42
  • I added some relevant information about lower_bound. – JKS Aug 19 '14 at 13:45
  • But you do not need (or want) to decrease the iterator. Although the 98/03 standards got the wording wrong, the hint is *supposed* to be to immediately *after* where the insertion will take place, so what `lower_bound` returns is the correct iterator to use as a hint (and the C++11 standard corrected the wording to reflect this). – Jerry Coffin Aug 19 '14 at 13:46
  • 3
    Erm, don't you mean "checking it doesn't point to the begin iterator"? You're trying to back up one position and you need to check that you don't step off of the beginning of your container. (Decrementing `end()` is OK, decrementing `begin()` is not.) – Andre Kostur Aug 19 '14 at 13:55
  • @JKS: the problem is not with the iterator, but what is expected of hints. When using a hint to insert or emplace, you are to give an iterator not before but after, which is exactly what `lower_bound` yields. Note therefore that the OP's question is misinformed: you need to decrement to get an iterator to the greatest element that still compares inferior to yours, but should not decrement to use as hint. – Matthieu M. Aug 19 '14 at 14:22