-4

I am inserting key value pairs in a std::map as

key = //something;
value = //something;
demoMap[key] = value;

Printing the key and value here gives me correct results. However, when I iterate this map as:

for( std::map<std::string, std::string>::iterator it = demoMap.begin();
     it != demoMap.end(); it++ ) {
    std::cout << it->first + "," << it->second;
}

Using above iteration, I get the second key value pair printed before the first one. Why is it so? The first key value pair should be printed first since the iterator of the map is set to begin() for the map.

Kamalpreet Grewal
  • 822
  • 1
  • 13
  • 28

1 Answers1

4

A std::map is not ordered by insertion order, but through ordering of the keys which is by default obtained with operator< on the keys.

For std::string the default operator< uses lexicographical ordering, so keys will be iterated in that order only.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Jack
  • 131,802
  • 30
  • 241
  • 343