矢量序列化 [英] vector serialization
问题描述
我正在尝试二进制序列化数据的向量。在下面的示例中,我序列化到一个字符串,然后反序列化回一个向量,但不会得到相同的数据,我开始。为什么会出现这种情况?
I am trying to binary serialize the data of vector. In this sample below I serialize to a string, and then deserialize back to a vector, but do not get the same data I started with. Why is this the case?
vector<size_t> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
string s((char*)(&v[0]), 3 * sizeof(size_t));
vector<size_t> w(3);
strncpy((char*)(&w[0]), s.c_str(), 3 * sizeof(size_t));
for (size_t i = 0; i < w.size(); ++i) {
cout << w[i] << endl;
}
我希望得到输出
I expect to get the output
1
2
3
$ b b
但是得到输出
but instead get the output
1
0
0
(位于 gcc-4.5.1 )
推荐答案
错误在于调用 strncpy
。从链接的页面:
The error is in the call to strncpy
. From the linked page:
如果 src 的长度小于 n ,strncpy()填充dest的剩余部分与空字节。
If the length of src is less than n, strncpy() pads the remainder of dest with null bytes.
因此,在找到序列化数据中的第一个 0
字节后的剩余
w
的数据数组用 0
填充。
So, after the first 0
byte in the serialized data is found the remainder of w
's data array is padded with 0
s.
要解决此问题,请使用 for
循环或 std :: copy
To fix this, use a for
loop, or std::copy
std::copy( &s[0],
&s[0] + v.size() * sizeof(size_t),
reinterpret_cast<char *>(w.data()) );
IMO,而不是使用 std :: string
作为缓冲区,只需使用 char
数组来保存序列化数据。
IMO, instead of using std::string
as a buffer, just use a char
array to hold the serialized data.
这篇关于矢量序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!