Obtaining list of keys and values from unordered_map

后端 未结 4 1694
陌清茗
陌清茗 2020-12-13 08:22

What is the most efficient way of obtaining lists (as a vector) of the keys and values from an unordered_map?

For concreteness, suppose the

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 08:34

    Using C++-14 you could also do the following (edited to contain full source):

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    typedef string Key;
    typedef int Value;
    
    auto key_selector = [](auto pair){return pair.first;};
    auto value_selector = [](auto pair){return pair.second;};
    
    int main(int argc, char** argv) {
      // Create a test map
      unordered_map map;
      map["Eight"] = 8;
      map["Ten"] = 10;
      map["Eleven"] = 11;
    
      // Vectors to hold keys and values
      vector keys(map.size());
      vector values(map.size());
    
      // This is the crucial bit: Transform map to list of keys (or values)
      transform(map.begin(), map.end(), keys.begin(), key_selector);
      transform(map.begin(), map.end(), values.begin(), value_selector);
    
      // Make sure this worked: Print out vectors
      for (Key key : keys) cout << "Key: " << key << endl;
      for (Value value : values) cout << "Value: " << value << endl;
    
      return 0;
    }
    

    I compiled this with the following command:

    g++ keyval.cpp -std=c++14 -o keyval
    

    Testing it printed the keys and values as expected.

提交回复
热议问题