检查多种可能性的相等性的简写

Red*_*Owl 8 c++

可能重复:
C++将一堆值与给定值进行比较

我需要在C++中检查for循环中的相等性,但是循环需要适用于x等于多种可能性.

例如,现在我有类似的东西:

if(x==a || x==b || x==c || x==d || x==e || x==f || x==g || x==h)
{
    //loop body
}
Run Code Online (Sandbox Code Playgroud)

但是随着我的数量,它看起来很乱,我想知道是否有一种简写方式说"if(x ==(其中任何一个))"或者如果将它们全部写出来是唯一的选择.

谢谢!

小智 5

谢谢你的问题,现在当我找到一个解决方案(我敢说是一个优雅的解决方案)时,我会自己使用它。

与 std::find 的解决方案不同:a)会在编译时展开 N 次比较 b)适用于 X 可以与之比较的任何类型

struct TagAnyOf {};

template <typename... Args>
std::tuple <TagAnyOf, Args...> AnyOf (Args&&... args)
{
   return std::tuple <TagAnyOf, Args...> (TagAnyOf(), std::forward<Args>(args)...);
}

template <class X, class Tuple, size_t Index, size_t ReverseIndex>
struct CompareToTuple
{
    static bool compare (const X& x, const Tuple& tuple)
    {
        return x == std::get<Index> (tuple) || CompareToTuple<X, Tuple, Index+1, ReverseIndex-1>::compare (x, tuple);
    }
};

template <class X, class Tuple, size_t Index>
struct CompareToTuple <X, Tuple, Index, 0>
{
    static bool compare (const X& x, const Tuple& tuple)
    {
        return false;
    }
};

template <typename X, typename... Args>
bool operator == (const X& x, const std::tuple<TagAnyOf, Args...>& any)
{
    typedef std::tuple <TagAnyOf, Args...> any_of_type;
    return CompareToTuple <X, any_of_type, 1, std::tuple_size<any_of_type>::value-1>::compare (x, any);
}
Run Code Online (Sandbox Code Playgroud)

用法

int main()
{
    int x = 1;
    if (x == AnyOf (1, 2, 3, 4))
    {
        std::cout << "Yes!" << std::endl;
    }
    else
    {
        std::cout << "No!" << std::endl;
    }

    if (x == AnyOf (4, 3, 2, 1))
    {
        std::cout << "Yes!" << std::endl;
    }
    else
    {
        std::cout << "No!" << std::endl;
    }

    if (x == AnyOf (2, 3, 4, 5))
    {
        std::cout << "Yes!" << std::endl;
    }
    else
    {
        std::cout << "No!" << std::endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Tre*_*key 2

考虑使用采用initializer_list 的函数(这是c++11 的功能)。
第一个参数将是左手值(在您的情况下是 x ),其余参数将是右手值。


这是使用模板完成任务的示例。

#include <iostream>
#include <cstdlib>
#include <algorithm>

template<class T> 
bool Test(T const& test, std::initializer_list<T> const& values){
    return std::find(std::begin(values), std::end(values), test) != std::end(values);
}

int main(){

    char var1 = 'a';
    char var2 = 'a';
    char var3 = 'b';
    char var4 = 'c';
    char var5 = 'd';

    if (Test<char>(var1,{var2,var3,var4,'o',var5})){
        std::cout << "true. at least one is equivelent" << std::endl;
    }else{
        std::cout << "false. none are equivelent" << std::endl;
    }

    if (Test<char>(var1,{var3,var4,var5})){
        std::cout << "true. at least one is equivelent" << std::endl;
    }else{
        std::cout << "false. none are equivelent" << std::endl;
    }

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

如果您对类执行此操作,请确保重载“!=”运算符。

编辑:错误已修复。GManNickG 指出