cpx
cpx

Reputation: 17557

How to check whether an array contains a unique value

I want to check for all values in an array:

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

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

Upvotes: 5

Views: 3782

Answers (3)

Stephen
Stephen

Reputation: 49156

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

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

Or with std::count:

if (int n = count(array, end(array), 7)) {
  cout << "Array contains " << n << " 7s!";
}

Upvotes: 5

TheUndeadFish
TheUndeadFish

Reputation: 8171

There is no built-in operator to do such a thing.

There are numerous ways to perform the test as what appears to be a single statement from the outside. And some of which use parts already provided by the standard library, so that you wouldn't have to write much code yourself. However, they will inevitably use some form of function call and/or loop at some point which you already ruled out.

So given the restrictions in your question: No, there isn't any way.

Upvotes: 2

Brendan Long
Brendan Long

Reputation: 54242

Depending on the problem, you might want to use a set. It has a member function called count() that tells you if something is in the set:

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

Upvotes: 4

Related Questions