Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a value with all array elements in one statement

Tags:

c++

For example:

if (value == array[size]) //if the value (unique) is present in an array then do something

can this be done in one statement without having to call a function or a basic for loop statement?

like image 836
cpx Avatar asked Jun 30 '10 00:06

cpx


People also ask

How do you compare all elements in an array?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do you compare values in an array?

A simple way is to run a loop and compare elements one by one. Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).

How do you compare two elements in the same array?

equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

std::find can do it in one statement, but it's not as trivial as other languages :(

int array[10];
if (array + 10 != find(array, array + 10, 7)) {
  cout << "Array contains 7!";
}

Or with std::count:

if (int n = count(array, array + 10, 7)) {
  cout << "Array contains " << n << " 7s!";
}
like image 89
Stephen Avatar answered Sep 29 '22 20:09

Stephen