将 std::vector的内容复制到进入 char* 缓冲区?
我有一个 std::vector 。我想将向量的内容复制到一定大小的 char* 缓冲区中。
有安全的方法吗?
我可以这样做吗?
memcpy(buffer, _v.begin(), buffer_size);
或者这个?
std::copy(_v.begin(), _v.end(), buffer); // throws a warning (unsafe)
或者这个?
for (int i = 0; i < _v.size(); i++)
{
*buffer = _v[i];
buffer++;
}
谢谢..
I have an std::vector. I want to copy the contents of the vector into a char* buffer of a certain size.
Is there a safe way to do this?
Can I do this?
memcpy(buffer, _v.begin(), buffer_size);
or this?
std::copy(_v.begin(), _v.end(), buffer); // throws a warning (unsafe)
or this?
for (int i = 0; i < _v.size(); i++)
{
*buffer = _v[i];
buffer++;
}
Thanks..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您只需要
char*
,那么您可以这样做:注意更改
buffer
指向的数据也会更改向量的内容!或者,如果您需要副本,则分配大小等于
v.size()
字节的内存,并使用std::copy
:完成后不要忘记
删除 []buffer;
,否则会泄漏内存。但是为什么会出现这样的问题,需要您管理记住你自己......尤其是当你可以做得更好时,例如:
希望有帮助。
If you just need
char*
, then you can do this:Note changing data pointed to by
buffer
changes the vector's content also!Or if you need a copy, then allocate a memory of size equal to
v.size()
bytes, and usestd::copy
:Dont forget to
delete []buffer;
after you're done, else you'll leak memory.But then why would you invite such a problem which requires you to manage the memory yourself.. especially when you can do better, such as:
Hope that helps.
将
vector
复制到char *
缓冲区的最安全方法是将其复制到另一个向量,然后使用该向量的内部缓冲区:当然,您可以如果您实际上不需要复制数据,也可以访问
_v
的缓冲区。另外,请注意,如果调整向量的大小,指针将失效。如果您需要将其复制到特定的缓冲区中,那么您需要在复制之前知道该缓冲区足够大;数组上没有边界检查。检查完尺寸后,第二种方法是最好的。 (第一个仅在
vector::iterator
是指针时有效,但不能保证;尽管您可以将第二个参数更改为&_v[0]
以使第三个做同样的事情,但更复杂,可能应该修复,这样它就不会修改缓冲区)。The safest way to copy a
vector<char>
into achar *
buffer is to copy it to another vector, and then use that vector's internal buffer:Of course, you can also access
_v
s buffer if you don't actually need to copy the data. Also, beware that the pointer will be invalidated if the vector is resized.If you need to copy it into a particular buffer, then you'll need to know that the buffer is large enough before copying; there are no bounds checks on arrays. Once you've checked the size, your second method is best. (The first only works if
vector::iterator
is a pointer, which isn't guaranteed; although you could change the second argument to&_v[0]
to make it work. The third does the same thing, but is more complicated, and probably should be fixed so it doesn't modifybuffer
).好吧,对于情况 3,您想分配给
*buffer
,但这应该可行。第一个几乎肯定行不通。编辑:我对#2 的看法是正确的。
Well, you want to assign to
*buffer
for case 3, but that should work. The first one almost certainly won't work.EDIT: I stand corrected regarding #2.
然后:
但记得稍后删除 []src
and then:
but remember to delete []src later
这是在 C++ 中执行此操作的首选方法。如果缓冲区足够大,则以这种方式复制是安全的。
This is preferred way to do this in C++. It is safe to copy this way if
buffer
is large enough.