C++ 如何检查多个变量是否等于相同的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8196796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check whether multiple variables are equal to the same value?
提问by Dani
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 是否都等于字符 'X' 或所有三个都等于 'O'。(如果其中 2 个是 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?
但它没有用。做这个的最好方式是什么?
回答by Dani
if((A == 'X' || A == 'O') && A == B && B == C)
{
// Do whatever
}
回答by Steve Jessop
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')) { ... }
回答by Seth Carnegie
Just seperate them and test them one by one:
只需将它们分开并一一测试:
if (A == 'O' && B == 'O' && C == 'O' || A == 'X' && B == 'X' && C == 'X')
// etc