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++?
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());
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.