C++ Adding 2 arrays together quickly

前端 未结 6 1804
一整个雨季
一整个雨季 2021-02-04 16:57

Given the arrays:

int canvas[10][10];
int addon[10][10];

Where all the values range from 0 - 100, what is the fastest way in C++ to add

6条回答
  •  忘掉有多难
    2021-02-04 17:39

    Here is an alternative.

    If you are 100% certain that all your values are between 0 and 100, you could change your type from an int to a uint8_t. Then, you could add 4 elements together at once of them together using uint32_t without worrying about overflow.

    That is ...

    uint8_t  array1[10][10];
    uint8_t  array2[10][10];
    uint8_t  dest[10][10];
    uint32_t *pArr1 = (uint32_t *) &array1[0][0];
    uint32_t *pArr2 = (uint32_t *) &array2[0][0];
    uint32_t *pDest = (uint32_t *) &dest[0][0];
    
    int  i;
    
    for (i = 0; i < sizeof (dest) / sizeof (uint32_t); i++) {
        pDest[i] = pArr1[i] + pArr2[i];
    }
    

    It may not be the most elegant, but it could help keep you from going to architecture specific code. Additionally, if you were to do this, I would strongly recommend you comment what you are doing and why.

提交回复
热议问题