How do I compare multiple items? For example, I wish to check if all the variables A, B, and C are equal to the char 'X' or all three are equal to 'O'. (If 2 of them are X and one is O it should return false.)
如何比较多个项目?例如,我想检查所有变量A,B和C是否等于char'X'或者所有三个都等于'O'。 (如果其中两个是X而一个是O则应该返回false。)
I tried:
if (A, B, C == 'X' || A, B, C == 'O') { //Do whatever }
but it didn't work. What is the best way to do this?
但它不起作用。做这个的最好方式是什么?
3 个解决方案
#1
15
if((A == 'X' || A == 'O') && A == B && B == C){ // Do whatever}
#2
11
Just for variety:
只是为了变化:
template <typename T, typename U>bool allequal(const T &t, const U &u) { return t == u;}template <typename T, typename U, typename... Others>bool allequal(const T &t, const U &u, Others const &... args) { return (t == u) && allequal(u, args...);}if (allequal(a,b,c,'X') || allequal(a,b,c,'O')) { ... }
#3
0
Just seperate them and test them one by one:
只需将它们分开并逐一测试:
if (A == 'O' && B == 'O' && C == 'O' || A == 'X' && B == 'X' && C == 'X') // etc
#1
15
if((A == 'X' || A == 'O') && A == B && B == C){ // Do whatever}
#2
11
Just for variety:
只是为了变化:
template <typename T, typename U>bool allequal(const T &t, const U &u) { return t == u;}template <typename T, typename U, typename... Others>bool allequal(const T &t, const U &u, Others const &... args) { return (t == u) && allequal(u, args...);}if (allequal(a,b,c,'X') || allequal(a,b,c,'O')) { ... }
#3
0
Just seperate them and test them one by one:
只需将它们分开并逐一测试:
if (A == 'O' && B == 'O' && C == 'O' || A == 'X' && B == 'X' && C == 'X') // etc