C++: Fastest method to check if all array elements are equal
int check(const int a[], int n)
{
while(--n>0 && a[n]==a[0]);
return n!=0;
}
C++ how to check if elements in an array are equal?
for (unsigned i = 0; i < val; i++) {
if (a[i] != a[0]) {
return false;
}
}
return true;
That ought to do it.
In this case, the code will instantly fail on a non-matching value. However, on a matching value it simply continues checking (as we know we need to test EVERY element of the array no matter what). Once that's done, it knows everything went well (since we didn't return early) and returns true.
Fastest method to check if all elements of 2d array are equal
Your current code will fail because break
will only take you out of one loop. You must exit both, which requires a second check, like so:
auto the_value = houses[0][0];
bool equal = true;
for(int j=0;j<5;j++){
for(int k=0;k<6;k++){
if(houses[j][k]!=the_value){
equal = false;
goto done;
}
}
if(!equal)
break
}
(Storing the first element in a variable and then looping over all of the elements to check to see if they are equal to that variable obviates the mess you invoke by checking adjacent elements.)
Breaking out of both loops simultaneously requires the Dark Arts (goto
), but may be more readable/maintainable if you are disciplined and may be slightly faster, depending on your compiler:
auto the_value = houses[0][0];
bool equal = true;
for(int j=0;j<5;j++)
for(int k=0;k<6;k++)
if(houses[j][k]!=the_value){
equal = false;
goto done; //Danger, Will Robinson!
}
done:
//More stuff
You may find a flat array to be faster:
auto the_value = houses[0][0];
bool equal = true;
for(int i=0;i<5*6;i++)
if(houses[i]!=the_value){
equal = false;
break;
}
The 2D array is stored as a 1D contiguous array in memory. Using flat array addressing accesses the same memory locations, but explicitly avoids forcing the internal arithmetic. For highly performant code you may wish to consider using flat arrays by default.
Since you might use a function such as this a number of times or have it embedded in otherwise complex code, perhaps you'd like to abstract it:
template<class T>
bool AllEqual(const T& arr, size_t N){
T the_value = arr[0];
for(int i=0;i<N;i++)
if(arr[i]!=the_value)
return false;
return true;
}
AllEqual(houses, 5*6);
Since you're coding in C++, you probably don't want to be using raw arrays anyway. Let's rewrite your code using the STL, assuming flat arrays:
template<class T>
bool AllEqual(const std::vector<T>& arr){
return std::all_of(arr.begin(), arr.end(), [&](const T& x){ return x==arr[0]; });
}
std::vector<int> houses = {}; //Replace with appropriate initialization
if(AllEqual(houses))
//Do stuff
(Also: as another answerer mentioned, the way you are adding data to your array seems to imply that it should be 2x6/6x2 array instead of 5x6/6x5.)
How to check if numbers in array equal?
You can solve this question using the following program of linear search. The following program will not only report the array elements which are equal but also the number of array elements which are equal. Incase any mistakes please let me know :)
#include <stdio.h>
int main()
{
int a[10], i, j, flag = 0;
printf("Please Enter 10 Numbers");
for(i = 0; i < 10; i++)
scanf("%d", &a[i]);
for(i = 0; i < 10; i++)
{
for(j = i + 1; j < 10; j++)
{
if(a[i] == a[j])
{
flag++;
printf("Array Element %d and %d are equal", i, j);
}
}
}
printf("\nThe Equal Numbers In The Array Are = %d", flag);
return 0;
}
A quick way to test whether all array elements are zero
Or use:
for (i=0; i<10; i++)
if (a[i])
break;
if (i==10) printf("No repeated digits");
else {
//...
}
Checking if all elements of a vector are equal in C++
You need not to use std::sort
. It can be done in a simpler way:
if ( std::adjacent_find( myvector.begin(), myvector.end(), std::not_equal_to<>() ) == myvector.end() )
{
std::cout << "All elements are equal each other" << std::endl;
}
Checking if all elements of a vector are equal in C++
You need not to use std::sort
. It can be done in a simpler way:
if ( std::adjacent_find( myvector.begin(), myvector.end(), std::not_equal_to<>() ) == myvector.end() )
{
std::cout << "All elements are equal each other" << std::endl;
}
Check if all elements in an array are equal
All you need to change is the termination condition in the for
loop to
i < newArr.Length - 1
so that you can compare array[i]
with array[i + 1]
. This change makes sure you do not get past the upper bound of the array.
Related Topics
Making a Borderless Window with for Qt
A Way in C++ to Hide a Specific Function
Linux Optimistic Malloc: Will New Always Throw When Out of Memory
Why Is Operator!= Removed in C++20 for Many Standard Library Types
Std::Array with Aggregate Initialization on G++ Generates Huge Code
How to Use a Custom Type as Key for a Map in C++
Can Std::Vector Emplace_Back Copy Construct from an Element of the Vector Itself
When Is Explicit Move Needed for a Return Statement
Gcc -Wuninitialized/-Wmaybe-Uninitialized Issues
Cost of Throwing C++0X Exceptions
Convert Char Array to Single Int
Some Clarification Needed About Synchronous Versus Asynchronous Asio Operations
Why Sizeof Built in Types Except Char Is Compiler Dependent in C & C++