33

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

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
LocalToast
  • 397
  • 1
  • 5
  • 13

2 Answers2

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
    Here N is const? array N should be const. – notbad Jan 22 '14 at 07:48
  • @notbad Yes, `N` is const (guess I should've used `n` as posted in the question) – Praetorian Jan 22 '14 at 07:54
  • 4
    There's also `std::move`. Sadly, not `std::move_n`. – R. Martinho Fernandes Jan 22 '14 at 09:40
  • 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
  • 1
    Instead 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