How do I copy or move the first n
elements of a std::vector<T>
into a C++11 std::array<T, n>
?
Asked
Active
Viewed 3.0k times
33

Shafik Yaghmour
- 154,301
- 39
- 440
- 740

LocalToast
- 397
- 1
- 5
- 13
-
12[`std::copy_n`](http://en.cppreference.com/w/cpp/algorithm/copy_n). – Some programmer dude Jan 22 '14 at 07:40
-
Do you want to copy, or move? These are different things. – juanchopanza Jan 22 '14 at 07:45
-
Depending on what `::std::vector` contains, `::std::memcpy` and `::std::memmove` could also be used. – user1095108 Jan 22 '14 at 07:49
-
1or in C++ the `std::uninitialized_copy` :) – legends2k Jan 22 '14 at 07:49
2 Answers
48
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());

Praetorian
- 106,671
- 19
- 240
- 328
-
1
-
@notbad Yes, `N` is const (guess I should've used `n` as posted in the question) – Praetorian Jan 22 '14 at 07:54
-
4
-
what happens if the size N is wrong? i.e. vector has 5 elements, array wants to copy 10? The cpp doc page is a bit unclear on this. – peter karasev Dec 04 '14 at 08:31
-
@peterkarasev The number of elements you pass to `copy_n` needs to be the minimum of the sizes of the vector and the array. Otherwise you'll either read beyond the bounds of the source or write beyond the bounds of the destination, both of which are undefined behavior. – Praetorian Dec 04 '14 at 17:03
-
1@Praetorian undefined... so, some compiler might throw exception, elsewhere it will overwrite some memory? I would hope it throws exception, otherwise what's the gain over the raw array that silently trashes memory when going out of bounds? – peter karasev Dec 06 '14 at 21:19
10
You can use std::copy
:
int n = 2;
std::vector<int> x {1, 2, 3};
std::array<int, 2> y;
std::copy(x.begin(), x.begin() + n, y.begin());
And here's the live example.
If you want to move, instead, you can use std::move
:
int n = 2;
std::vector<int> x {1, 2, 3};
std::array<int, 2> y;
std::move(x.begin(), x.begin() + n, y.begin());
And here's the other live example.

Shoe
- 74,840
- 36
- 166
- 272
-
What about the `n`? Shouldn't it be `std::copy(x.begin(), x.begin() + n, y.begin());`? – legends2k Jan 22 '14 at 07:45
-
1Instead of using a variable such as `n`, wouldn't it be better to use `x.size()`? – Arnav Borborah Jun 07 '17 at 14:53
-
You could use `x.size()` but it won't compile - N here is a compile-time constant and even a template parameter. The `std::array` is simply like an array - it requires a size known at compile time. Period. – foo Jul 23 '21 at 13:15