How do I copy or move the first n
elements of a std::vector<T>
into a C++11 std::array<T, n>
?
The elements of a vector are contiguous. Otherwise, you just have to copy each element: double arr[100]; std::copy(v. begin(), v.
The standard algorithm for copying is std::copy . We can use it for copying elements from the source vector to the destination vector.
Use std::copy_n
std::array<T, N> arr; std::copy_n(vec.begin(), N, arr.begin());
Edit: I didn't notice that you'd asked about moving the elements as well. To move, wrap the source iterator in std::move_iterator
.
std::copy_n(std::make_move_iterator(v.begin()), N, arr.begin());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With