1

I tried to run following code:

std::map < std::string, std::string > m;
m[ "one" ] = "0";
m[ "two" ] = "1";
m[ "three" ] = "2";
m[ "four" ] = "3";

auto it = m.begin();
std::cout << it->first << "\n";

The output is: "four". But why does it start from the end? I was expected "one"!

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
JavaRunner
  • 2,455
  • 5
  • 38
  • 52

2 Answers2

5

The reason is that std::map is a sorted container. It sorts its elements, which are key-value pairs, according to the key, which is std::string in your particular case.

Then, strings are lexicographically compared with each other. As the string four is the smallest one among all the strings, the pair ("four", "3") becomes the first pair. So begin() returns the iterator which points to this pair.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
0

I'm not sure, but I think the std::map sorts the key elements for fast searching. (I believe it uses binary search). If you don't want the order to change you hace to use std::vector or std::list or std::deque something like that.

Sam
  • 2,473
  • 3
  • 18
  • 29