17

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?

Community
  • 1
  • 1
Steve Barna
  • 1,378
  • 3
  • 13
  • 23
  • 11
    In C++, **always** use `std::copy` rather than `memcpy` (the former will delegate to the latter when possible). – ildjarn Oct 12 '12 at 20:51
  • 1
    I don't know how fast it is, but you could use `std::copy`. – Code-Apprentice Oct 12 '12 at 20:52
  • 1
    I think the most obvious answer here would be: _Why do (you think) you need to copy from the vector into an array?_ A vector _is_ an array, and can be used as such. As a side effect, _no copying at all_ is certainly the fastest possible copying operation. – sbi Oct 13 '12 at 12:18

4 Answers4

39

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
13

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);
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
7

Try this:-

  std::vector<int> newvector(oldvector);

For copying in an array try this:-

  std::copy(source.begin(), source.end(), destination);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
3

You can use memcpy with a vector - vectors are guaranteed to be contiguous in memory so provided that the vector is not empty, you can use &vData[0] (where vData is your vector) as your source pointer to memcpy

EDIT As mentioned by comments to other answers, this only works if the vector's value_type is trivially copyable.

mathematician1975
  • 21,161
  • 6
  • 59
  • 101