Obtaining list of keys and values from unordered_map

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

    Joining late, but thought this might be helpful to someone.
    Two template functions making use of key_type and mapped_type.

    namespace mapExt
    {
        template
        std::vector Keys(const myMap& m)
        {
            std::vector r;
            r.reserve(m.size());
            for (const auto&kvp : m)
            {
                r.push_back(kvp.first);
            }
            return r;
        }
    
        template
        std::vector Values(const myMap& m)
        {
            std::vector r;
            r.reserve(m.size());
            for (const auto&kvp : m)
            {
                r.push_back(kvp.second);
            }
            return r;
        }
    }
    

    Usage:

    std::map mO;
    std::unordered_map mU;
    // set up the maps
    std::vector kO = mapExt::Keys(mO);
    std::vector kU = mapExt::Keys(mU);
    std::vector vO = mapExt::Values(mO);
    std::vector vU = mapExt::Values(mU);
    

提交回复
热议问题