Is the order of iterating through std::map known (and guaranteed by the standard)?

What I mean is – we know that the std::map‘s elements are sorted according to the keys. So, let’s say the keys are integers. If I iterate from std::map::begin() to std::map::end() using a for, does the standard guarantee that I’ll iterate consequently through the elements with keys, sorted in ascending order?


Example:

std::map<int, int> map_;
map_[1] = 2;
map_[2] = 3;
map_[3] = 4;
for( std::map<int, int>::iterator iter = map_.begin();
     iter != map_.end();
     ++iter )
{
    std::cout << iter->second;
}

Is this guaranteed to print 234 or is it implementation defined?


Real life reason: I have a std::map with int keys. In very rare situations, I’d like to iterate through all elements, with key, greater than a concrete int value. Yep, it sounds like std::vector would be the better choice, but notice my “very rare situations”.


EDIT: I know, that the elements of std::map are sorted.. no need to point it out (for most of the answers here). I even wrote it in my question.
I was asking about the iterators and the order when I’m iterating through a container. Thanks @Kerrek SB for the answer.

7 Answers
7

Leave a Comment