Probably would be easier to have a vector in parallel with the map and the index would be the order. You can also use boost::multi_index https://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/tutorial/index.html Answer from DoctorMixtape on reddit.com
๐ŸŒ
Cplusplus
cplusplus.com โ€บ reference โ€บ map โ€บ map
std::map
Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order. In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ map-vs-unordered_map-c
map vs unordered_map in C++ - GeeksforGeeks
The C++ map container is ideal for situations where data needs to be stored in sorted order and when you need to efficiently access the predecessor or successor of a specific element.
Published ย  May 19, 2025
Discussions

Why did C++ standard library name the containers map and unordered_map instead of map and ordered_map? - Programming Language Design and Implementation Stack Exchange
A map as a mathematical object (function) is by default "unordered", and the same is for maps as a data structure AKA associative arrays or dictionaries (python). So why did they choose to name the ordered map (usually a binary search tree) std::map and the map data structure (usually a hashmap) ... More on langdev.stackexchange.com
๐ŸŒ langdev.stackexchange.com
July 19, 2024
Are c++ std::map<string,string> ordered? - Stack Overflow
are STL maps ordered? Specifically I need to know if std::map is ordered. So if I iterate over it, it will iterate with the first insert string first. So will the below iterate A, C then B consis... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to sort a map according to value?
Maps are designed to be sorted by their key, not their value. It doesn't make sense to sort an existing map by value as it simply isn't laid out in a way that makes that possible. You could always take each value and put them in a different container (such as another map, a vector or a set) and have that sorted by value. More on reddit.com
๐ŸŒ r/cpp_questions
17
1
May 29, 2023
c++ - How to ensure that a std::map is ordered? - Stack Overflow
Using a std::map how can I ensure at inserting time that iterating over it will take place in ascending order of the integer key? More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ how to create std::map that preserves the order of insertion just using standard c++?
r/cpp_questions on Reddit: How to create std::map that preserves the order of insertion just using standard C++?
September 18, 2022 - Thatโ€™s not how a map works. A map doesnโ€™t store the entries in the order they are entered, because you canโ€™t have the fast lookup that way.
๐ŸŒ
W3Schools
w3schools.com โ€บ cpp โ€บ cpp_maps.asp
C++ Maps
Since map elements consist of both keys and values, you have to include .first to access the keys, and .second to access values in the loop. Elements in the map are sorted automatically in ascending order by their keys:
๐ŸŒ
GitHub
github.com โ€บ Tessil โ€บ ordered-map
GitHub - Tessil/ordered-map: C++ hash map and hash set which preserve the order of insertion ยท GitHub
The ordered-map library provides a hash map and a hash set which preserve the order of insertion in a way similar to Python's OrderedDict. When iterating over the map, the values will be returned in the same order as they were inserted.
Starred by 573 users
Forked by 78 users
Languages ย  C++ 97.4% | CMake 2.6%
๐ŸŒ
cppreference.com
en.cppreference.com โ€บ cpp โ€บ container โ€บ unordered_map
std::unordered_map - cppreference.com
References and pointers to either key or data stored in the container are only invalidated by erasing that element, even when the corresponding iterator is invalidated. ... #include <iostream> #include <string> #include <unordered_map> int main() { // Create an unordered_map of three strings (that map to strings) std::unordered_map<std::string, std::string> u = { {"RED", "#FF0000"}, {"GREEN", "#00FF00"}, {"BLUE", "#0000FF"} }; // Helper lambda function to print key-value pairs auto print_key_value = [](const auto& key, const auto& value) { std::cout << "Key:[" << key << "] Value:[" << value <<
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ map-associative-containers-the-c-standard-template-library-stl
Map in C++ STL - GeeksforGeeks
Maps are associative containers that store keyโ€“value pairs in sorted order using a self-balancing Red-Black Tree.
Published ย  May 11, 2026
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ descending-order-map-multimap-c-stl
Descending Order in Map and Multimap of C++ STL - GeeksforGeeks
July 23, 2025 - How to store elements in reverse order or descending order when inserting in map and multimap? We can use the third parameter, that is std::greater along with map and multimap to store elements in descending order. Descending order in the map: ...
Top answer
1 of 3
25

The short answer: Historical reasons.

Alexander Stepanov's philosophy was always that the algorithms come first. One analogy he always liked was with mathematics. When mathematicians present their work, they generally start with the axioms and work forwards. But when they are actually developing their work, they generally start with the interesting theorems and work backwards.

It's the similar story with the Standard Template Library. He believed that the interesting algorithms come first, and the data structures and their APIs get designed around them. This was especially important if the algorithms were to be generic.

The very earliest versions of the libraries that eventually became Standard Template Library (e.g. the Ada Generic Library Linear Data Structure Packages) didn't include associative containers such as maps and multimaps. Notably, they were also not pitched to the C++ standards committee in the earliest presentations.

Since the Ada Generic Library and original Standard Template Library were designed around algorithms, the interesting algorithms were generally on containers of a single type. When you have containers of single types, it's more or less clear what an "iterator" should look like, for example.

But associative containers have two interesting types: a "key" type and a "value" type. So what does a generic algorithm "iterate" on? Keys? Key-value pairs? We know what Stepanov and Lee eventually settled on, but it had to be worked out.

And that's just the API between containers and generic algorithms. The other difficult part of the API is how a programmer should present their own user-defined types to the STL.

C++ has native syntax for overloading the less-than and equal-test operators. And these need to be implemented already to write generic sort algorithms. Programmers find it quite easy to provide a less-than comparison for their user-defined types compared to, say, a radix query, which is why "library" sort functions tend to be comparison-based rather than radix-based.

In that context, it was clear that implementing associative containers that are based on comparisons was going to be easier and less controversial than ones based on hashing. Hash tables would require designing an API for providing user-declared hash functions. Unlike comparison, C++ didn't have "native" hash function support, so it needed to be designed, and it wasn't clear what the "right" design should be.

(This is a little off track, but it's also worth noting that the research community also wasn't clear as to whether or not "generic" algorithms on hash tables should be "aware" of hash table structure in some way.)

There was an early proposal for adding hash tables to the C++ standard library, more or less tracking HP's implementation, but it was too late to make it into the C++98 standard. What happened in the mean time is that third-party vendors wrote their own hash_map/hash_set (and the multi-variants) implementations that were all broadly similar, but subtly mutually incompatible.

The Boost project was started in 1998 by members of the C++ committee, in part to be a test lab for new proposals to be added to the C++ standards library. When it came time to experiment with hash tables, in around 2003, Jeremy Maitin-Shepard chose unordered rather than hash for Boost's implementation, essentially because none of the vendors had chosen that name, so there's no chance that they would clash.

Boost's proposal eventually was adopted into TR1, and subsequently C++11.

TL;DR version:

Languages like Perl, Python, and ECMAScript started with the data structures and did the algorithms later, which is why the hash tables get the simpler names. C++ started with the algorithms and did the data structures later, which is why the ordered search trees got the simpler names.

2 of 3
4

Historical accident. map was part of the original Standard Template Library approved by ANSI/ISO in 1994. std::unordered_map was added to the C++ standard library with C++ 11.

๐ŸŒ
Quora
quora.com โ€บ Is-a-map-already-sorted-in-C
Is a map already sorted in C++? - Quora
Answer (1 of 4): Yes, itโ€™s based on a balanced binary search tree. The tree can be traversed in order to obtain a sorted list of keys. There is also unordered_map, which is a hash table and not sorted in any obvious way (itโ€™s sorted by hash).
๐ŸŒ
Medium
medium.com โ€บ @yakupcengiz โ€บ comparing-std-map-and-std-unordered-map-in-c-92aa18c5dc39
Comparing std::map and std::unordered_map in C++ | by Yakup Cengiz | Medium
July 28, 2023 - This is due to the constant-time average complexity of unordered map lookups, while std::map requires logarithmic time complexity for search operations. When the keys are generated in an ordered manner (using GenerateOrderedKeyList), the results show that std::unordered_map consistently outperforms std::map in both insertion and search operations.
๐ŸŒ
Programiz
programiz.com โ€บ cpp-programming โ€บ map
C++ Map
In C++, maps are associated containers that hold pairs of data. These pairs, known as key-value pairs, have a unique key, while the associated values don't have to be unique. ... The elements in a map are internally sorted by their keys. In order to use maps in C++, we must include the map ...
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ cplusplus-programming โ€บ 140505-possible-specify-ordering-std-map.html
Is is possible to specify the ordering of a std::map ?
I did what I needed manually with some 30 lines of code(setting the precedences), but the ordering would have made it possible to make a loop for that. ... Bolding "map" and "to" doesn't change the fact that you're probably using the wrong data structure. std::map is basically just a balanced binary search tree.
๐ŸŒ
cppreference.com
en.cppreference.com โ€บ cpp โ€บ container โ€บ map
std::map - cppreference.com
Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as Redโ€“black trees. Iterators of std::map iterate in ascending order of keys, where ascending is defined by the comparison that was ...
๐ŸŒ
Quora
quora.com โ€บ Should-I-use-map-or-unordered_map-in-C
Should I use map or unordered_map in C++? - Quora
Answer (1 of 9): I am tempted to say that โ€œjust use unordered_mapโ€ and leave happily because I gave an awesome advice, but I think I am going to elaborate a bit just for the sake of it! It is very unfortunate that when the C++ standard comitee decided to include in the standard library ...
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ how to sort a map according to value?
r/cpp_questions on Reddit: How to sort a map according to value?
May 29, 2023 - Or a dofferent dictionary data structure, which can keep an order separate for key order. ... You can never make the map "sort" by value. Its fundamentally a tree structure mapping from key to value.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ sorting-a-map-by-value-in-c-stl
Sorting a Map by value in C++ STL - GeeksforGeeks
July 15, 2025 - The idea is to insert all pairs from the given map into multimap using the originals map's value as a key in the multimap and original maps key value as a value in the multimap. Below is the implementation of the above approach: ... // C++ program ...
Top answer
1 of 3
36

You don't have to do anything. The map will be in ascending order according to the values of the key.

Internally, the map performs a comparison between keys to order its elements. By default, it uses std::less<KEY>, which is equivalent to bool operator<(int, int) for integers. For user defined types, you have to options:

  1. Implement a bool operator<(const MyType&, const MyType&) implementing a strict weak ordering comparison between your user defined types. Use this if your type has a natural ordering

  2. Provide a binary functor that implements strict weak ordering, which you can pass as the 3rd template parameter to the map. Use this if your type does not have a natural ordering, or if you want to build the map with an ordering different to that used by std::less<Key> via the bool operator<(...) from point 1.

What typically happens behind the scenes is that the map is implemented as a self-balancing binary tree, and the strict weak ordering is used to place new elements in the map, and to determine whether two elements are equal. As an aside, the same logic applies to std::set, where the key and value are one and the same.

2 of 3
20

std::map does that itself. You don't have to do anything.

By default it sorts the keys in the increasing order. If you want it to do sorting in decreasing order, then pass std::greater<T> as third template argument to std::map.

std::map<int, X>  m1;                    //sorts key in increasing order
std::map<int, X, std::greater<int>>  m2; //sorts key in decreasing order
std::map<int, X, std::less<int>> m3;     //sorts key in increasing order

The default argument for third template parameter is std::less<T>, so above m1 and m3 are same types!

Demo:

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::cout << "\nkeys are in increasing order: \n";
    std::map<int, std::string> m1;
    m1[5] = "first insertion but higher key";
    m1[1] = "second insertion but lower key";
    for(auto const & item : m1) 
       std::cout << "{" << item.first  <<"," << item.second << "}\n";

    std::cout << "\nkeys are in decreasing order: \n";   
    std::map<int, std::string, std::greater<int> > m2;
    m2[1] = "first insertion but lower key";
    m2[2] = "second insertion but higher key";
    for(auto const & item : m2) 
       std::cout << "{" << item.first  <<"," << item.second << "}\n";
}

Output:

keys are in increasing order: 
{1,second insertion but lower key}
{5,first insertion but higher key}

keys are in decreasing order: 
{2,second insertion but higher key}
{1,first insertion but lower key}

Notice that in both cases the items are ordered as specified by the third template argument of std::map. The output doesn't depend on the order of insertion, rather the order of the keys!

Live demo

There is also std::unordered_map which doesn't sort elements.

๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ c++ โ€บ unordered_map
C++ (C Plus Plus) | unordered_map | Codecademy
June 20, 2025 - The constant-time lookup makes it ideal for systems that need to frequently access employee information by ID, such as payroll systems or HR applications. A map maintains elements in sorted order using a balanced binary search tree (typically red-black tree), providing O(log n) operations, while unordered_map uses a hash table with O(1) average-case operations but no ordering guarantees.