Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memcpy to copy the contents of a vector<double> into a memory buffer

Tags:

c++

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)

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[]()

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!

like image 711
Walt Dizzy Records Avatar asked Mar 24 '14 06:03

Walt Dizzy Records


People also ask

Does memcpy work with vectors?

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.

What is memcpy used for in C++?

The memcpy() function in C++ copies specified bytes of data from the source to the destination. It is defined in the cstring header file.


1 Answers

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));
like image 180
D'artanian Avatar answered Oct 08 '22 05:10

D'artanian