I'm working on serialising std::map using sstream in C++. Serialising function:
template <class key, class value>
std::string serializeMap(const std::map<key, value>& v){
std::stringstream ss;
std::for_each(v.begin(), v.end(), [&ss](const std::pair<key, value>& s){
ss.write ((char*)&s, sizeof(std::pair<key,value>));
});
return ss.str();
}
And de-serialize using this:
template <class key, class value>
void deSerializeMap(const std::string& s, std::map<key, value>& v){
std::stringstream ss1;
ss1<<s;
int pos = 0;
printf("\nlen %d\n", s.size());
while(ss1){
char* ar = new char[sizeof(std::pair<key, value>)];
ss1.read(ar, sizeof(std::pair<key, value>));
v.insert(*(reinterpret_cast<std::pair<key, value>*>(ar)));
pos+=sizeof(std::pair<key, value>);
ss1.seekg(pos);
delete[] ar;
}
}
This works as expected using std::string
. I had to use a C function that takes const char*
as an argument, I tried using c_str()
and adding a NULL character to the char array, but strlen
gives zero. Is there something I'm missing?
Aucun commentaire:
Enregistrer un commentaire