使用memcpy复制vector< double>的内容.到内存缓冲区 [英] Using memcpy to copy the contents of a vector<double> into a memory buffer
问题描述
我有一个包装矢量的类:
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; }
....
}
实例为:
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?
使用 std :: copy
(感谢WhozCraig)
Use std::copy
(thanks to 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
解决方案失败
尝试使用 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
仍然对为什么我的原始代码失败感到好奇!
推荐答案
我尝试了3种不同的方法,所有这些方法都可以工作.data()方法是正确执行此操作的方法.如果不起作用,请检查数据是否以某种方式损坏.
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.
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));
这篇关于使用memcpy复制vector< double>的内容.到内存缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!