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

后端 未结 10 2005
庸人自扰
庸人自扰 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).

提交回复
热议问题