Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to copy the contents of a vector into an array? [duplicate]

Tags:

c++

vector

Possible Duplicate:
How to convert vector to array C++

When working with arrays you have the ability to use

memcpy( void *destination, const void *source, size_t num );

However vectors simply provide iterators for a copy method, rendering memcpy useless. What is the fastest method for copying the contents a vector to another location?

like image 244
Steve Barna Avatar asked Oct 12 '12 20:10

Steve Barna


People also ask

How do you copy an element from a vector to an array?

Use copy() Function to Convert a Vector to an Array The copy() method can be utilized to convert a vector to a double array so that data elements are copied to a different memory location. Later, we can modify them without worrying about altering the original vector data.

How much faster are arrays 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.


2 Answers

std::copy, hands down. It’s heavily optimised to use the best available method internally. It’s thus completely on par with memcpy. There is no reason ever to use memcpy, even when copying between C-style arrays or memory buffers.

like image 196
Konrad Rudolph Avatar answered Oct 04 '22 16:10

Konrad Rudolph


You'll have to measure that for yourself, in your environment, with your program. Any other answer will have too many caveats.

While you do that, here is one method you can compare against:

std::copy(source.begin(), source.end(), destination);
like image 39
Robᵩ Avatar answered Oct 04 '22 17:10

Robᵩ