问题描述
struct MyData {
MyType dataA;
std::string dataB;
int dataC;
};
typedef std::pair<std::string,MyData> PairType;
std::map<PairType::first_type,PairType::second_type> dataMap;
这是在从库中调用函数的编译单元的头文件中定义的。
由于库函数不了解我的类型定义,因此无法直接传递dataMap。
该函数实际上只需要dataA
的结构成员,并且已经知道MyType
,因此我可以改为传递一个std::map<std::string,MyType>
。
从结构图中仅剪切我需要的数据,然后将其保存到具有相同键但仅包含dataA
的类型和值的新映射中,最优雅的方法是什么?
对于不使用boost或其他外部库的C ++ 0x而言,是最好的选择,但出于教育目的,也欢迎采用较新标准的解决方案。
我基本上是在寻找与Python相当的产品
newDict = {key:value.dataA for (key,value) in oldDict.items()}
解决方法
您可以使用基于范围的for循环来真正轻松地进行复制。看起来像
std::map<std::string,MyType> my_type_map;
for (const auto& pair : dataMap)
{
my_type_map.emplace(pair.first,pair.second.dataA);
}
,
如果您希望将其作为单个表达式,则将需要boost::transform_iterator
之类的东西,要么包含该表达式,要么自己编写一个迭代器。
给出转换函数(或等效的lambda)
std::pair<std::string,MyType> convert(PairType& pair){
return { pair.first,pair.second.dataA };
};
您可以声明newDict
并填充
/* can be const */ std::map<std::string,MyType> newDict {
boost::make_transform_iterator(oldDict.begin(),convert),boost::make_transform_iterator(oldDict.end(),convert)
};
auto newDict = boost::copy_range<std::map<std::string,MyType>>(oldDict | std::ranges::views::transform(convert));