Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 check(int array[], int n) {        bool flag = 0;      for(int i = 0; i < n - 1; i++)           {                  if(array[i] != array[i + 1])             flag = 1;     }      return flag; } 
like image 736
Harish Vishwakarma Avatar asked Jan 02 '13 10:01

Harish Vishwakarma


People also ask

How do you check if all array elements are the same?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.

How do you check if all the elements in a 2d array are same?

We can simply way to check if all the elements inside that array are equal or not. just assign the first row & column element in a variable. Then compare each element. If not equal then return false.


1 Answers

int check(const int a[], int n) {        while(--n>0 && a[n]==a[0]);     return n!=0; } 
like image 139
CubeSchrauber Avatar answered Sep 20 '22 15:09

CubeSchrauber