0

I am getting an exception with the following code snippet:

//      matlab mex program ...
float *ptr=new float[n*m];
.
.
.
std::vector<float> v(n*m);
v.assign(ptr);

How do I correctly assign ptr to the vector v?

1
  • ptr=new *float[nm] -> ptr=new float[nm]; Commented Mar 22, 2014 at 21:43

1 Answer 1

2

You can use either the constructor or assign, as you tried. However, you need to pass the length in some way. In the standard library, it's a common idiom to do this by passing the begin and end of a sequence - but those can be bare pointers. Like this:

std::vector<float> v; // Note you do not need the size here
v.assign(ptr, ptr+n*m);

or just:

std::vector<float> v(ptr, ptr+n*m);

It also seems like you have an error in your allocation:

float *ptr=new float[n*m]; // Allocate floats, not pointers to floats
Sign up to request clarification or add additional context in comments.

2 Comments

How copy the pointer in pointer of std::vector<float> ?? avoiding too many data copy in the vector<float>.
You cannot, as that would violate encapsulation. However, you can get the a pointer to the data in the vector and only use that instead of using new to allocate memory: float* ptr = v.data();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.