jeudi 26 octobre 2017

Using std::transform to convert a std::vector

Given these types:

struct MyVecType { int a; int b; };
typedef std::map<int, int> MyMap;
typedef std::vector<MyVecType> MyVector;

I can do this for serialisation (my serialisation library doesn't support map-like types):

MyVecType map2pair(std::pair<int, int> const &myPair)
{
    MyVecType retVal;
    retVal.a = myPair.first;
    retVal.b = myPair.second;
    return retVal;
}

MyMap myMap = {...};
MyVector myVector;
std::transform(myMap.begin(),
               myMap.end(),
               std::back_inserter(myVector),
               map2pair);

I then send the vector over to the receiver which wants to reconstruct the MyMap. However, I cannot find a suitable <algorithm> template that does de-serialisation like this:

MyMap myNewMap;
for (auto const &entry: myVector)
    myNewMap[entry.a] = entry.b;

How would I write this using an <algorithm>?

(Note my real case has a complex structure as the structure for the std::map value that actually has another serialised std::map inside it)

Aucun commentaire:

Enregistrer un commentaire