Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning different sized std::array

I have a populated std::array with meaningful data and a std::array with 0s. I wish to assign the array of 6 to the array of 8. What is the idiomatic way of doing this in c++?

like image 578
Jonathan Evans Avatar asked Nov 07 '25 14:11

Jonathan Evans


2 Answers

You could use std::copy if the destination array is larger than the source one:

std::array<int, 6> arr1;
std::array<int, 10> arr2;
// Fill arr1...
std::copy(arr1.begin(), arr1.end(), arr2.begin());

If the destination array is shorter, then you'll have to copy up to a certain point. I mean, you can still do this using std::copy, but you'll have to do something like:

std::array<int, 10> arr1;
std::array<int, 6> arr2;
// Fill arr1...
std::copy(arr1.data(), arr1.data() + arr2.size(), arr2.begin());

This works for both cases:

std::copy(arr1.data(), arr1.data() + std::min(arr1.size(), arr2.size()), arr2.begin());
like image 123
mfontanini Avatar answered Nov 10 '25 10:11

mfontanini


It's not quite clear what you're asking exactly so this answer covers several possibilities:

#include <array>
#include <algorithm>

int main() {
  // Uninitialized std::array
  std::array<int, 1> arr1;

  std::array<int, 2> arr2 = {0,1};

  // Not legal, sizes don't match:
  // std::array<int, 3> arr3 = arr2;

  // Instead you can do:
  std::array<int, 3> arr3;
  std::copy(arr2.begin(), arr2.end(), arr3.begin());

  // If the sizes match and the types are assignable then you can do:
  std::array<int, 3> arr4 = arr3;

  // You can also copy from the bigger to the smaller if you're careful
  std::copy_n(arr3.begin(), arr1.size(), arr1.begin());
}
like image 45
Flexo Avatar answered Nov 10 '25 10:11

Flexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!