C++: Fastest method to check if all array elements are equal

后端 未结 10 1887
庸人自扰
庸人自扰 2020-12-01 12:50

What is the fastest method to check if all elements of an array(preferable integer array) are equal. Till now I have been using the following code:

bool chec         


        
相关标签:
10条回答
  • 2020-12-01 13:25

    In theory, I would propose this:

    bool check_single(const int a[], int n)
    {
        for (int i = 1; i < n; ++i) {
            if (a[0] != a[n]) { return false; }
        }
        return true;
    }
    

    Compared to other (already proposed) versions:

    • a[0] will be hoisted outside the loop by the compiler, meaning a single array access within the loop
    • we loop from 0 to n, which is better (access-wise) than loading a[0] and then looping from a[n]

    Obviously, it still checks N elements and thus is O(N).

    0 讨论(0)
  • 2020-12-01 13:30

    Recast the array to a larger data type. Eg, operate on 64bit ints, or use SSE or AVX intrinsics for 128 or 256 bit operation. For example, the SSE2 intrinsic is _mm_cmpeq_epi32, whose result you'll use with _mm_or_si128. Check the result with repeated application of _mm_srli_si128 and _mm_cvtsi128_si32. Check the result every few hundred iterations for early exit.

    Make sure to operate on aligned memory, check the unaligned start and end as ints, and check the first packed element with itself.

    0 讨论(0)
  • 2020-12-01 13:30

    We'll it's basically an O(n) operation so you can't do much better than what you have, other than dispensing with the flag and just return false; on the first failure and return true; after the iteration.

    0 讨论(0)
  • 2020-12-01 13:30

    For programmer efficiency you may try the following all in one line.

    vector<int> v{1, 1, 1, 1};
    all_of(v.cbegin(), v.cend(), [&r=v[0]](int value){ return value == r; }->bool);
    

    I did not test run this code, let me know if there is syntax error.

    0 讨论(0)
提交回复
热议问题