在C++中,如何在不编写显式循环的情况下添加大小相同的两个数组?例如:
int a[3]={1,2,3};
int b[3]={4,3,2};
int c[3]; //to contain sum of a and b
如果明确的循环不可行,则可以使用可能隐含的循环。让标准库替你完成。
std::transform(a, a + 3, b, c, std::plus<int>{});
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>{});
}
编译器会很友好地为您检查大小。而且您甚至不必停在那里。有很多方法可以使add_arrays
在更多的上下文中可用。
话虽如此,尽量避免使用原始数组。默认情况下使用std::array
。它是对原始数组的薄包装,但具有值语义。如果您需要某个目的的固定集合(比如进行图形编程,因此需要存储坐标),请尝试使用指定类型。
#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,而是使用现有的优秀库之一。
这样的C++库的例子:
std::valarray
。这大致是它的用途。 - Cheers and hth. - Alfstd::valarray
就是我在寻找的东西。 - mibrahimy