Reputation: 732
How do we add two arrays of the same size without writing an explicit loop in C++ For example:
int a[3]={1,2,3};
int b[3]={4,3,2};
int c[3]; //to contain sum of a and b
Upvotes: 5
Views: 2269
Reputation: 10982
If you really want no loop and performance you can try that:
#include <emmintrin.h>
#include <iostream>
alignas(16) int32_t a[4] = {1, 2, 3, 0};
alignas(16) int32_t b[4] = {4, 3, 2, 0};
alignas(16) int32_t c[4];
main()
{
__m128i simd_a = _mm_load_si128((__m128i*)a);
__m128i simd_b = _mm_load_si128((__m128i*)b);
// No loop for addition and performance is here.
//
__m128i simd_c = _mm_add_epi32(simd_a, simd_b);
_mm_store_si128((__m128i*)c, simd_c);
std::cout << "\n" << c[0] << " " << c[1] << " " << c[2] << " " << c[3];
}
More seriously if your vectors are smalls and if performance is a real concern you can use SIMD. Do not recode simd yourself, but use one of the excellent libraries that are available.
Examples of such C++ libraries:
Upvotes: 1
Reputation: 170211
If an explicit loop is out of the question, then use a possibly implicit one. Let the standard library do it for you.
std::transform(a, a + 3, b, c, std::plus<int>{});
If you find yourself doing it on arrays of the same size often, you can even templatize it:
template<typename T, std::size_t N>
void add_arrays( T (const &a)[N], T (const &b)[N], T (&c)[N] ) {
std::transform(a, a + N, b, c, std::plus<T>{});
}
The compiler will be nice and check the sizes for you. And you don't even have to stop there. There's loads of ways to make add_arrays
usable in more contexts.
Having said all that. Try to shift away from using raw arrays. Use std::array
as a default. It's a thin wrapper over a raw array, but it has value semantics. And if you need a fixed collection of things for some purpose (say you are doing graphics programming, so you store coordinates), try to use designated types for it instead.
Upvotes: 5