简体   繁体   中英

How to output C++11 unordered_map/unordered_set and Java HashMap/HashSet values by input order?

How can I output a hashmap values by key's input order? In C++11 unordered_map, it's not ordered. Look at the C++ reference page

http://www.cplusplus.com/reference/unordered_map/unordered_map/begin/

  mymap = {{"Australia","Canberra"},{"U.S.","Washington"},{"France","Paris"}};
  std::cout << "mymap contains:";
  for ( auto it = mymap.begin(); it != mymap.end(); ++it )
    std::cout << " " << it->first << ":" << it->second;

The output sequence is

mymap contains: France:Paris Australia:Canberra US:Washington

However I expect Australia:Canberra US:Washington France:Paris

How do I output above result? And how to implement in Java(I test in HashSet/HashMap, keys are not ordered too)?

Thanks!

In Java, you can use LinkedHashMap and LinkedHashSet . Here is an example with LinkedHashMap , that prints the entries in the same order as they were inserted into the map:

Map<String, String> map = new LinkedHashMap<>();
map.put("Australia", "Canberra");
map.put("U.S.", "Washington");
map.put("France", "Paris");
for (Map.Entry<String, String> e : map.entrySet()) {
    System.out.printf("%s:%s\n", e.getKey(), e.getValue());
}

For C++ take a look at Boost Multi-Index Containers . You can find a similar example in the tutorial in the section about sequenced indices . In your case, it might look as follows:

struct country
{
    std::string name;
    std::string capital;
};

multi_index_container<
    country,
    indexed_by<
        hashed_unique<member<country,std::string,&country::name>>
        sequenced<>>> countries;

the unordered_map in itself is conceptually unordered :-)

but think about maintaining a list of keys to keep track of the insertion order

then

for (auto& key : KeyOrderList)
    cout << "(" << key << ", " << MyMap[key] << ")" << endl;
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;
int main(int argc, char *argv[]) {
    unordered_map<std::string, std::string> mymap = {{"Australia", "Canberra"},{"U.S.","Washington"},{"France","Paris"}};
    vector<std::string> keys;
    transform(mymap.begin(), mymap.end(), back_inserter(keys),
        [](const decltype(mymap)::value_type& pair) {
            return pair.first;
        });
    sort(keys.begin(), keys.end());
    cout << "mymap contains: ";
    for (auto const& key: keys) {
        cout << " " << key << ":" << mymap[key];
    }
    cout << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM