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

后端 未结 10 1974
庸人自扰
庸人自扰 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:11

    Once you have found a mismatching element you can break out of the loop:

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

    If this is performance-critical then it can be further optimised slightly as:

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

提交回复
热议问题