原型與指針類型有點奇怪。如果我們可以假設將它們固定到
void serialize(const Map& myMap, char* buf, size_t bufSize);
Map deserialize(char const* buf, size_t bufSize);
下面是使用升壓序列化實現他們一個演示程序:
Live On Coliru
#include <unordered_map>
#include <string>
#include <iostream>
typedef std::unordered_map<int, std::string> Map;
void serialize(const Map& myMap, char* buf, size_t bufSize);
Map deserialize(char const* buf, size_t bufSize);
int main() {
char buffer[4096];
serialize({ { 1, "one" }, { 2, "two" }, /* etc */ }, buffer, sizeof(buffer));
auto data = deserialize(buffer, sizeof(buffer));
for (auto p : data)
std::cout << p.first << " -> " << p.second << "\n";
}
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/serialization/unordered_map.hpp>
#include <boost/serialization/string.hpp>
void serialize(const Map& myMap, char* buf, size_t bufSize)
{
boost::iostreams::stream<boost::iostreams::array_sink> os(buf, bufSize);
boost::archive::binary_oarchive oa(os);
oa << myMap;
}
Map deserialize(char const* buf, size_t bufSize)
{
boost::iostreams::stream<boost::iostreams::array_source> is(buf, bufSize);
boost::archive::binary_iarchive ia(is);
Map data;
ia >> data;
return data;
}
打印
1 -> one
2 -> two
問題編輯。對之前缺乏清晰度表示歉意。 – user3685928