Search code examples
c++stdmapyosys

Does operator of `[]` of std::map always put the new item into the first place of iterator?


Hi I've met a problem relating to iterator order of inserted values in std::map by operator [].

The code is a github program in line 265: many_async_rules[rstval].insert(sync_level);

The definition of the map is std::map<RTLIL::SigSpec, std::set<RTLIL::SyncRule*>> many_async_rules;

By testing cases and guessing its meaning, this line should insert the rstval into the first iterator slot of many_async_rules.

However, in my machine it actually put the rstval into the last of it.

Thus I would like to ask if this is normal in std::map??

The following is some system info of my computer:

[shore@shore-82b6 yosys]$ gcc --version
gcc (GCC) 11.2.0
Copyright © 2021 Free Software Foundation, Inc.
[shore@shore-82b6 yosys]$ cat /etc/lsb-release
DISTRIB_ID=ManjaroLinux
DISTRIB_RELEASE=21.2.6
DISTRIB_CODENAME=Qonos
DISTRIB_DESCRIPTION="Manjaro Linux"

Any extra info needed, please leave comment.


Solution

  • Elements of std::map are stored in order of the key established by the Compare predicate that was provided to the map (by default, std::less). If rstval is the least key according to the predicate, then it will be the first element. If rstval is the greatest key according to the predicate, then it will be the last element.

    Which means that if the key is a pointer, then the order is not sure??

    If the key is a pointer, and the predicate is std::less, and if the pointers are to elements of an array, then the order is the same as the order of the pointed elements in that array. But if the pointers are not to elements of an array, then their relative order is unspecified.