Compare the value with all array elements in a single expression

For instance:

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

can this be done in one statement without calling a function or basic loop operator?

+5
source share
3 answers

std::find can do this in one statement, but it is 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!";
}
+5
source

Depending on the problem you may use set. It has a member function called count()that tells you if there is anything in the set:

if(myset.count(value) > 0){
    doThings();
}
+4
source

.

There are many ways to run a test, like what seems to be the only expression from the outside. And some of them use parts already provided by the standard library, so you don’t have to write a lot of code yourself. However, they will inevitably use some function call and / or loop at some point that you have already excluded.

So, given the limitations in your question: No, there is no way.

+2
source

All Articles