C++ 使用 memcpy 将 vector<double> 的内容复制到内存缓冲区中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22602486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using memcpy to copy the contents of a vector<double> into a memory buffer
提问by Elegant Codeworks
I have a class that wraps a vector:
我有一个包装向量的类:
template <typename T>
class PersistentVector
{
private:
std::vector<T> values;
public:
std::vector<T> & getValues() throw () { return values; }
....
}
The instance is:
实例是:
PersistentVector<double> moments;
I am trying to make a copy of all the doubles into a buffer allocated by somebody else. Here is where I create the buffer:
我试图将所有双打的副本复制到其他人分配的缓冲区中。这是我创建缓冲区的地方:
// invariant: numMoments = 1
double * data_x = new double[numMoments];
Here is my attempt at copying the contents of the vector into the buffer:
这是我将向量的内容复制到缓冲区中的尝试:
double theMoment = moments.getValues()[0];
// theMoment = 1.33
std::memcpy(
data_x,
&(moments.getValues().operator[](0)),
numMoments * sizeof(double));
// numMoments = 1
double theReadMoment = data_x[0];
// theReadMoment = 6.9533490643693675e-310
As you can see, I am getting a garbage value from the buffer. Why is this so?
如您所见,我从缓冲区中获取了一个垃圾值。为什么会这样?
Working solution
工作解决方案
Use std::copy
(thanks to WhozCraig)
使用std::copy
(感谢 WhozCraig)
double theMoment = moments.getValues()[0];
// theMoment = 1.33
std::copy(moments.getValues().begin(), moments.getValues().end(), data_x);
double theReadMoment = data_x[0];
// theReadMoment = 1.33
Failed solution
失败的解决方案
Try data()
instead of operator[]()
尝试data()
代替operator[]()
double theMoment = moments.getValues()[0];
// theMoment = 1.33
std::memcpy(
data_x,
moments.getValues().data(),
numMoments * sizeof(double));
// numMoments = 1
double theReadMoment = data_x[0];
// theReadMoment = 6.9533490643693675e-310
Still curious as to why my original code is failing!
仍然很好奇为什么我的原始代码失败了!
采纳答案by D'artanian
I tried doing this in 3 different ways and all of them worked. The data() method is the way to do it right. If it does not work - check if the data was corrupted in some way.
我尝试以 3 种不同的方式执行此操作,并且所有方法都有效。data() 方法是正确的方法。如果它不起作用 - 检查数据是否以某种方式损坏。
std::vector<double> vec1 = {1.33,2.66,3.99};
double* vec2 = new double[3];
int numMoments = 1;
::memcpy(
vec2,
vec1.data(),
numMoments * sizeof(double));
::memcpy(
vec2,
&(*vec1.begin()),
numMoments * sizeof(double));
::memcpy(
vec2,
&(vec1[0]),
numMoments * sizeof(double));