tags:

views:

109

answers:

3

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?

+4  A: 

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!";
}
Stephen
neat, but why complicate the simple things? which does not buy anything (performace or readibilty)
Gollum
@Gollum, OP asked for it in one statement, I gave it to him in one statement. ;) I would not personally use this approach for arrays. It's simpler with other containers, or with a `contains` helper function.
Stephen
@Gollum, how is this complicated C++? Do you suggest spreading this find() call over more lines??
catchmeifyoutry
The only thing that could be considered *"complicated"* is the way the iterators are constructed, which can be improved by using utility functions like `begin()`/`end()` from Boost.Range, or that the intent is not clear enough, in which case some `contains()` utility function can be used.
Georg Fritzsche
@stephen, @catchmeifyoutry by *complicate* I meant not conveying intent. as @George points out. otherwise, I have seen a lot of these in Lion's book.
Gollum
Don't downvote just because you don't _like_ a solution. It's the answer to what the OP asked, and it's not wrong.
Stephen
@stephen, I din't.
Gollum
@Gollum : I knew it wasn't you :), someone came along later, +1'd you and -1'd me.
Stephen
+4  A: 

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();
}
Brendan Long
And if you just want to know if it's in there one or more times:`if(myset.find(value) != myset.end()) { /*hooray!*/ }`
Duracell
@Duracell, sets can't have duplicates, so set.count returns 1 or 0. Both versions are equivalent.
Matthew Flaschen
@Matthew, that's true. I suppose it's a just a habit because I use `std::map::find` in the same way.
Duracell
@Duracell, if you're using a set that allows duplicates, you just use count still.
Brendan Long
+2  A: 

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.

TheUndeadFish