Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cheaply assign C-style array to std::vector?

Currently I do the following:

// float *c_array = new float[1024];  void Foo::foo(float *c_array, size_t c_array_size) {   //std::vector<float> cpp_array;    cpp_array.assign(c_array, c_array + c_array_size);   delete [] c_array; } 

How can I optimize this assigning? I would like not to perform elementwise copy but just swap pointers.

like image 819
Dmitriy Avatar asked Apr 29 '11 19:04

Dmitriy


People also ask

Can I assign an array to a vector C++?

To convert an array to vector, you can use the constructor of Vector, or use a looping statement to add each element of array to vector using push_back() function.

Are C style arrays faster than vectors?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

Is vector better than array C++?

Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.


1 Answers

The current std::vector doesn't provide any capability or interface to take ownership of previously allocated storage. Presumably it would be too easy to pass a stack address in by accident, allowing more problems than it solved.

If you want to avoid copying into a vector, you'll either need to use vectors through your entire call chain, or do it the C way with float[] the entire time. You can't mix them. You can guaranteed that &vec[0] will be equivalent to the C-array though, fully contiguous, so using vector in the whole program may be feasible.

like image 75
Mark B Avatar answered Sep 21 '22 06:09

Mark B