The
conditional operator is a ternary operator, i.e. it takes three operands (arguments).
operand1 ? operand2 : operand3
If the first operand evaluates to
true then it will evaluate the
second operand and use that as the result.
true ? a : b
→
a
If the first operand evaluates to
false then it will evaluate the
third operand and use that as the result.
false ? a : b
→
b
The type of the second and third operand needs to be similar so that the result of the whole expression can be converted to a "common type" (e.g.
int and
double will result in
double).
The reason your second code does not work is because all operands are expected to be
expressions.
return true
and
return false
are not
expressions. If you had put semicolons at the end they would have been
statements but a statement does not have a "type" and is not allowed here.
If all you really wanted was to write an if statement on a single line you can do that using a regular if statement. The C++ language does not prevent you from doing that although you might not see it that often due to readability/maintainability concerns.
1 2 3 4 5
|
template <typename T>
bool contains(vector<T> vec, const T& elem)
{
if (find(vec.begin(), vec.end(), elem) != vec.end()) return true; else return false;
}
|