Keep the order of unordered_map as we insert a new key

后端 未结 3 2112
抹茶落季
抹茶落季 2021-02-19 07:01

I inserted the elements to the unordered_map with this code:

    myMap.insert(std::make_pair(\"A\", 10));
    myMap.insert(std::make_pair(\"B\", 11         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 08:05

    Remarkably common request without too many clean,simple solutions. But here they are:

    1. The big library: https://www.boost.org/doc/libs/1_71_0/libs/multi_index/doc/tutorial/index.html Use unique index std::string (or is it char?) and sequenced index to retain the order.
    2. Write it yourself using 2 STL containers: Use a combination of std::unordered_map (or std::map if you want sorted key order traverse as well) and a vector to retain the sequenced order. There are several ways to set this up, depending on the types on your keys/values. Usually keys in the map and the values in the vector. then the map is map<"key_type",int> where the int points to the element in the vector and therefore the value.

    I might have a play with a simple template for a wrapper to tie the 2 STL containers together and post it here later...

    I have put a proof of concept up for review here:

    I went with std::list to store the order in the end, because I wanted efficient delete. But You might choose std::vector if you wanted random access by insertion order.

    I used a a list of Pair pointers to avoid duplicate key storage.

提交回复
热议问题