【发布时间】:2018-04-07 11:10:22
【问题描述】:
鉴于这些类型:
struct ComplexLibraryThing { /*lots of fields*/};
typedef std::map<int, ComplexLibraryThing> MyMap;
struct ShadowComplexLibraryThing { /*Shadow of ComplexLibraryThing*/};
struct MyVecType { int a; ShadowComplexLibraryThing b; };
typedef std::vector<MyVecType> MyVector;
我可以为序列化执行此操作(我的序列化库不支持类似地图的类型):
MyVecType map2pair(std::pair<int, ComplexLibraryThing> const &myPair)
{
MyVecType retVal;
retVal.a = myPair.first;
retVal.b = convertForSerialisation(myPair.second);
return retVal;
}
MyMap myMap = {...};
MyVector myVector;
std::transform(myMap.begin(),
myMap.end(),
std::back_inserter(myVector),
map2pair);
然后我将向量发送给想要重建MyMap 的接收器。但是,我找不到像这样进行反序列化的合适的<algorithm> 模板:
MyMap myNewMap;
for (auto const &entry: myVector)
myNewMap[entry.a] = convertForDeserialisation(entry.b);
我将如何使用<algorithm> 编写此内容?
(注意图中的ComplexLibraryThing类型不能轻易更改,但我也有一个ShadowComplexLibraryThing可以)
【问题讨论】:
-
你能修改
MyVecType吗?如,添加成员函数? -
你为什么不在另一端做同样的事情:
std::transform有一个函数?或者将std::for_each()与 lambda 结合起来?我想我错过了一些东西:-/ -
@piwi 我不确定用什么替换
std::back_inserter... -
您的修改没有回答我的问题。你能修改
MyVecType本身吗? -
顺便说一句,您有什么理由要使用算法吗?基于范围的 for 循环让我觉得比转换简单得多。 (特别是如果您将正文更改为
myNewMap.insert(std::make_pair(entry.a, convertForDeserialisation(entry.b));(这避免了默认构造映射条目然后分配给它。)。
标签: c++ c++11 stl stl-algorithm