C++ std::vector insert的行为与我预期的不一样。是虫子吗?
我一直在使用std::vector来存储从文件中读取的一些二进制数据,然后将其序列化为通过套接字发送的数据报。我为端到端功能编写了unittest,但由于意外原因失败:C++ std::vector insert的行为与我预期的不一样。是虫子吗?,c++,stdvector,C++,Stdvector,我一直在使用std::vector来存储从文件中读取的一些二进制数据,然后将其序列化为通过套接字发送的数据报。我为端到端功能编写了unittest,但由于意外原因失败: std::vector<char> buf; response->data(buf); ASSERT(1 == buf.size()); 和往常一样,我在提交问题后有了一个想法。插入是否保留当前内容并插入新值?也就是说,在调用insert之前,向量的大小应该调整为零字节 更新: 我在文档中遗漏了这个 The
std::vector<char> buf;
response->data(buf);
ASSERT(1 == buf.size());
和往常一样,我在提交问题后有了一个想法。插入是否保留当前内容并插入新值?也就是说,在调用insert之前,向量的大小应该调整为零字节 更新: 我在文档中遗漏了这个
The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.
std::insert()
插入新值并重新定位旧值。因此,你所描述的行为是意料之中的。您应该改用std::copy()
。我最后使用了assign()。它替换未指定类型的地址并基于该地址进行扩展。这似乎起了作用。这当然同样有效——我已经忘记了。另一句话:小心resize()
函数。如果向量已经包含一些数据,则不会重新初始化该向量。
buf.resize(sourceLen);
for (unsigned long i = 0; i < sourceLen; ++)
{
buf[i] = source[i];
}
ASSERT(1 == buf.size()); // Succeeds: buf.size() == 1.
buf.resize(sourceLen);
buf.insert(buf.begin(), data, data + dataLen - 1);
ASSERT(1 == buf.size()); // Succeeds: buf.size() == 1.
ASSERT(buf[0] == source[0]); // Fails: buf[0] == ''.
The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.