Add arrays without C ++ loop

How to 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
+4
source share
2 answers

If an explicit loop is out of the question, use an implicit perhaps. Let the standard library do it for you.

std::transform(a, a + 3, b, c, std::plus<int>{});

If you often do this on arrays of the same size, 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 are many ways to make add_arraysusable in other contexts.


. . std::array . , . (, , ), .

+4

, :

#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];
}

, , , SIMD. simd , .

++:

0

Source: https://habr.com/ru/post/1691168/


All Articles