In C++ say we have two arrays:
a[5] = {1,2,3,4,5};
b[5] = {5,4,3,2,1};
If we wanted to set, for instance, a equal to b, how can we achieve that without using a loop?
My thought is to use recursion, but I'm not exactly sure how.
Edit: Sorry, should have made it clear I don't want to use the standard library functions (including memcpy which some of you have mentioned)
int a[5] = {1,2,3,4,5};
int b[5] = {5,4,3,2,1};
memcpy(a, b, sizeof(a));
You can use the copy algorithm from the standard library.
std::copy(std::begin(b), std::end(b), std::begin(a));
std::begin
and std::end
are new in the C++ standard library, but they're easy to implement for compilers that don't support them yet:
template <typename T, std::size_t N>
T* begin(T(&a)[N]) {
return &a[0];
}
template <typename T, std::size_t N>
T* end(T(&a)[N]) {
return begin(a) + N;
}
Alternatively, you can use std::array
(or the equivalent from Boost for older compilers) and the assignment operator:
std::array<int, 5> a = {1,2,3,4,5};
std::array<int, 5> b = {5,4,3,2,1};
a = b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With