将map<key,value>重建为map<value,key的最短/最简单的方法>
shortest/easiest way to reconstruct map<key, value> into map<value, key>
如果我有静态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)
);
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- EASTL矢量<向量<int>>连续的
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 为什么我会" void value not ignored as it ought to be"?
- 方法错误"not all control paths return a value"和方法不返回值
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- 如何在 c++ 中理解这样的代码 [request->headers().Method()->value().getStringView())]
- std::<key-value>不同类型的对向量
- c++ visual studio 64bit | save registers value
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 如何解决类成员函数中的"return a value"错误?
- bsoncxx: document::view vs document::value
- .value( "key" , default) 不适用于空的 json 对象吗?
- 如何在C++中设置演员的"Render Custom Depth Pass"和"Depth Stencil Value"?
- Qt 错误:QSqlQuery::value:尝试从表中检索统计信息时未定位在有效记录上 (QComboBox)
- 马洛克会在 C++17 年返回"invalid pointer value"吗?
- 如何将 v8::FunctionCallbackInfo<v8::Value> 数组从一个隔离复制到另一个隔离?
- std::value templated 方法的函数使用 clang 和 g++ 进行编译,但不使用 msvc 进行编译
- 无法使用 auto 来参数化true_type来检测 T::value()
- 为什么使用 "++value"会导致 -842150449?