0

I have below map code in C++-

std::map<std::string, std::string> vals;
vals["%"] = "PERCENT";
vals["$"] = "DOLLAR";
vals["="] = "EQUAL";

With above code lines I expect % will be at index 0 and $ at index 1. But when I compile and debug I always find $ at index 0 and % at index 1.

anybody has any idea why this is happening? maintaining sequence is must for me , any suggestion how can I get rid of it.

Richard Dally
  • 1,362
  • 2
  • 20
  • 35
user987316
  • 884
  • 4
  • 11
  • 35

3 Answers3

3

That's because std::map sorts its content. The order of insertion doesn't matter. Here, it will sort on alphabetical order.(because the key value is std::string) Because $ has a lower value than % this means that $ == vals.begin(). This is also why user-defined types used as keys in a map require their operator< to be overloaded.

Hatted Rooster
  • 34,596
  • 6
  • 59
  • 115
1

There is no 'natural' standard dictionary container that preserves the order of insertion. Neither std::map nor std::unordered_map will do this. If you need to preserve the order of insertions, you need to use a container which can do this and insert std::pair<your_key_type, your_value_type>.

The obvious drawback of that is that uniqueness of your keys will no longer be enforced automatically, so that is something you will have to take care about - with huge performance penalty.

The 3 standard containers which will suit you are std::vector, std::deque and std::list, and the most performant one usually is the std::vector.

There are also third-party libraries (boost, for example) which have some containers which might suit you as well.

SergeyA
  • 59,974
  • 5
  • 72
  • 130
0

You can't think of the subscript operator as an array index in this case. For std::map operator is overloaded where the contents of [] is the templated type of your key. In this case you're using a string to string map and so you put strings inside of []. As far as how the contents are sorted when you iterate over the contents, I believe this STL implementation specific. However, looking at the link map you will see that you can optionally provide a comparitor that can override the default sort.

I think you'd have a hard time getting to a insertion order iteration, but that isn't the point of a map.

klog
  • 386
  • 3
  • 10