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

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

    Here is a solid solution which is valid C++11. The advantages is that you do not need to manually play with the indexes or iterators. It is a best practice to

    prefer algorithm calls to handwritten loops [Herb Sutter - C++ Coding Standards]

    I think this will equally efficient as Paul R's solution.

    bool check(const int a[], int n)
    {
          return !std::all_of(a, a+n, [a](int x){ return x==a[0]; });
    }
    
    0 讨论(0)
  • 2020-12-01 13:10

    Find a library that's available on your platform that supports threading or parallel-for loops, and split the computation out such that different cores test different ranges of the array.

    Some available libraries are listed here:

    http://parallel-for.sourceforge.net/parallelfor.html

    Or possibly, you can make use of the parallism that many GPU's offer.

    0 讨论(0)
  • 2020-12-01 13:10
    bool check_identity (int a[], int b[], const int size)
    {
        int i;
        i = 0;
        while ((i < size-1) && (a[i] == b[i]))   i++;
    
        return (a[i] == b[i]);
    
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-01 13:13
    int check(const int a[], int n)
    {   
        while(--n>0 && a[n]==a[0]);
        return n!=0;
    }
    
    0 讨论(0)
  • 2020-12-01 13:20
    bool check(int array[],int n)
    {       
      // here 1st element is checked with others. This decreases the number of iteration by 1.
      // also it returns immediately. 
      // The requirement is to check if all the elements are equal. 
      // So if 1st element is equal to others then all elements are equal. 
      // Otherwise the  elements are not equal.
      for(int i=1;i<n;i++)      
      {         
        if(array[0]!=array[i])
          return false;
      }        
      return true;
    }
    
    0 讨论(0)
提交回复
热议问题