使用比较运算符时检查多个值 [英] Check for multiple values when using comparison operators

查看:92
本文介绍了使用比较运算符时检查多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直给人的印象是,对于任何比较语句,即X == YX != Y是格式,并且您将语句与&&||链接在一起.

I've always been under the impression that for any comparison statement, i.e. X == Y or X != Y is the format, and you chain statements together with && or ||.

有没有什么方法可以代替X == Y || X == Z来编写X == (Y || Z)?

Is there not some way to write X == (Y || Z) instead of X == Y || X == Z?

编辑:由于已经确定不可能做到这一点,所以还可以怎么做?

Edit: Since it has been established that this is not possible to do cleanly, how else could it be done?

推荐答案

#include <algorithm>
#include <array>
#include <string>
#include <iostream>
#include <initializer_list>

template<class Type, class Next>
bool is_one_of(const Type& needle, const Next& next)
{return needle==next;}
template<class Type, class Next, class ... Rest>
bool is_one_of(const Type& needle, const Next& next, Rest... haystack)
{return needle==next || is_one_of(needle, haystack...);}

int main() {
    std::string X, Y;
    if (is_one_of(X, Y, "HI"))
        std::cout << "it is!";
    else
        std::cout << "it isn't!";
    return 0;
}

编译证明. Xeo 还会观察到std::any_ofstd::all_ofstd::none_of可能有用,具体取决于您的实际情况.需求和欲望.

proof of compilation. Xeo also observes that std::any_of, std::all_of and std::none_of may have been useful, depending on your actual needs and desires.

这篇关于使用比较运算符时检查多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆