Obtaining list of keys and values from unordered_map

后端 未结 4 1691
陌清茗
陌清茗 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:59

    Okay, here you go:

    std::vector keys;
    keys.reserve(map.size());
    std::vector vals;
    vals.reserve(map.size());
    
    for(auto kv : map) {
        keys.push_back(kv.first);
        vals.push_back(kv.second);  
    } 
    

    Efficiency can probably be improved, but there it is. You're operating on two containers though, so there's not really any STL magic that can hide that fact.

    As Louis said, this will work for any of the STL map or set containers.

提交回复
热议问题