问题
Given the the below two statements, could someone help me use only the ternary operator instead of if statements?
I have tried a lot to do that:
if(strstr(cv[i],a.c_str()))
{
o=1;
p=cv[i];
p=p.substr(a.size()+1);
}
else o+=4;
if (b^*s && c++ + 1 ^ *s)
{
cout << b;
if (b^--c)
cout << (c - b>1 ? "-" : ",") << c;
if (a)
cout << ",";
b = c = *s;
}
回答1:
The ternary operator is an expression, which returns a value when evaluated:
<result> = <condition> ? <when true> : <when false>
In this pseudo code <when true>
and <when false>
must also be an expression. Although you can pack several statements into a single expression with some trick (e.g. to embrace it with a do { <statements> } while(false);
structure), the ternary operator is not meant to be used for this. You should use a ternary operator when both the then
and the else
branches are consisted of a single statement, and optionally you may use the return value of the expression.
So to take a very simple example, instead of writing
if(x > 0)
y += 10;
else
y += 20;
It is cleaner and simpler to use a ternary operator:
y += x > 0 ? 10 : 20;
However it is not the case when the conditional branches contain multiple statements, as in that case the use of a ternary operator would just make your code look more confusing and harder to understand.
来源:https://stackoverflow.com/questions/23415957/how-to-correctly-use-the-ternary-operator