将map<key,value>重建为map<value,key的最短/最简单的方法>

shortest/easiest way to reconstruct map<key, value> into map<value, key>

本文关键字:value gt key map lt 最简单 方法 重建      更新时间:2023-10-16

如果我有静态map<K, V> m{{"m1", 1}, {"m2", 2}, ...},这是将其转换为具有相同对的map<V, K>的最简单方法,但现在值转键,键转值?

我想在类初始化代码中有这个。像这样:

class PseudoEnum{
   enum Enum{m1, m2, m3};
   static map<string, Enum> _strMapping = {{"m1", Enum::m1}, {"m2", Enum::m2}, ...};
   static map<Enum, string> _enumMapping = ??? // shortest possible init  
}
std::transform(m.cbegin(), m.cend(), std::inserter(other, other.begin()),
               [](auto const& p){
    return std::make_pair(p.second, p.first);
});

这应该足够了。你可以把它封装在一个函数中:

template<typename K, typename V>
auto invert_mapping(std::map<K,V> const& m)
{
    std::map<V,K> other;
    std::transform(m.cbegin(), m.cend(), std::inserter(other, other.begin()),
                   [](auto const& p){
        return std::make_pair(p.second, p.first);
    });
    return other;
}

则调用

static map<Enum, string> _enumMapping = invert_mapping(_strMapping);

如果你想就地初始化它,你可以使用Boost的转换迭代器:

auto tr = [](auto const& p){ return std::make_pair(p.second, p.first); };
std::map<Enum, std::string> _enumMapping(
    boost::make_transform_iterator(_strMapping.cbegin(), tr),
    boost::make_transform_iterator(_strMapping.cend(), tr)
);