Keep the order of unordered_map as we insert a new key

后端 未结 3 2101
抹茶落季
抹茶落季 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:08

    Not with an unordered associative data structure. However, other data structures preserve order, such as std::map which keeps the data sorted by their keys. If you search Stackoverflow a little, you will find many solutions for a data structure with fast key-based lookup and ordered access, e.g. using boost::multi_index.

    If it is just about adding values to a container, and taking them out in the order of insertion, then you can go with something that models a queue, e.g. std::dequeue. Just push_back to add a new value, and pop_front to remove the oldest value. If there is no need to remove the values from the container then just go with a std::vector.

提交回复
热议问题