Search code examples
c++dictionaryiteratortraversal

traverse the std::map with less than comparison between iterators


When I'd like to traverse a map in C++, we may use the following technique:

for (auto i = m.begin(); i != m.end(); i++)
{    ...    ... }

Why cannot we use the following instead:

for (auto i = m.begin(); i < m.end(); i++)
{    ...    ... }

My guess is because the elements in an associative container are not stored in sequential order like sequential containers, is that right?


Solution

  • The comparison operator < requires random access iterators.

    map only provides Bidirectional iterators. The reason is that you cannot say with just such an iterator if another iterator is before or after in constant time (yes, they are not one after the other in memory).

    As != is valid for all types of iterators, use it instead of the < version. It's portable if you change the container type.