Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set one array equal to another without a loop [closed]

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)

like image 219
nan Avatar asked Oct 24 '12 17:10

nan


2 Answers

int a[5] = {1,2,3,4,5};
int b[5] = {5,4,3,2,1};

memcpy(a, b, sizeof(a));
like image 168
egrunin Avatar answered Oct 19 '22 23:10

egrunin


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;
like image 42
R. Martinho Fernandes Avatar answered Oct 20 '22 00:10

R. Martinho Fernandes