I have some code which I need to serialize a vector into bytes, then send it to a server. Later on, the the server replies with bytes and I need to serialize it back into a vector.
I have managed to serialize into bytes okay, but converting back into a vector is getting the wrong values:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<double> v = {1, 2, 3};
std::cout << "Original vector: " << std::endl;
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
std::string str((char *)v.data(), sizeof(v[0])*v.size());
std::cout << "Vector memory as string: " << std::endl << str << std::endl;
std::cout << "Convert the string back to vector: " << std::endl;
auto rV = std::vector<double>(&str[0], &str[str.size()]);
for (auto i : rV){
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
This outputs:
Original vector:
1 2 3
Vector memory as string:
�?@@
Convert the string back to vector:
0 0 0 0 0 0 -16 63 0 0 0 0 0 0 0 64 0 0 0 0 0 0 8 64
What is going wrong with my conversion from a string to a vector, and how can I fix it?
1 2 3as a string?doubles must start on addresses that are multiples of 8, the CPU can't load them otherwise