How do you copy the contents of an array to a std::vector in C++ without looping?

c++, copy, stl, vector

Solution

If you can construct the vector after you've gotten the array and array size, you can just say:

std::vector<ValueType> vec(a, a + n);

...assuming `a` is your array and `n` is the number of elements it contains. Otherwise, `std::copy()` w/`resize()` will do the trick.

I'd stay away from `memcpy()` unless you can be sure that the values are plain-old data (POD) types.

Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values.

Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to `begin()`, and (`ptr + n`) is equivalent to `end()`.

Problem

I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a `std::vector`. I don't want to have to do the standard loop to `push_back` all the values individually, it would be nice if I could just copy it all using something similar to `memcpy`.

Original source