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?
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
Try data()
instead of 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!
You can use the Use memcpy for vector assignment parameter to optimize generated code for vector assignments by replacing for loops with memcpy function calls. The memcpy function is more efficient than for -loop controlled element assignment for large data sets. This optimization improves execution speed.
The memcpy() function in C++ copies specified bytes of data from the source to the destination. It is defined in the cstring header file.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With