Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy std::vector into std::array

How do I copy or move the first n elements of a std::vector<T> into a C++11 std::array<T, n>?

like image 812
LocalToast Avatar asked Jan 22 '14 07:01

LocalToast


People also ask

How do I copy a vector element to an array?

The elements of a vector are contiguous. Otherwise, you just have to copy each element: double arr[100]; std::copy(v. begin(), v.

Does STD vector copy?

The standard algorithm for copying is std::copy . We can use it for copying elements from the source vector to the destination vector.


1 Answers

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()); 
like image 102
Praetorian Avatar answered Oct 08 '22 14:10

Praetorian