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
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);