检查平等到多种可能性的速度 [英] Shorthand for checking for equality to multiple possibilities
问题描述
可能重复:
C ++将值与给定值进行比较
我需要检查在C的for循环中的相等,但是循环需要为x等于多个可能性。
I'm needing to check for equality in a for loop in C++, however the loop needs to work for x equaling multiple possibilities.
例如,现在我有类似的东西:
For example, right now I have something similar to:
if(x==a || x==b || x==c || x==d || x==e || x==f || x==g || x==h)
{
//loop body
}
我有,它看起来混乱,我想知道是否有一个简写的方式说if(x ==(任何这些)或如果写出所有的是唯一的选择。
But with the number I have, it looks messy and I was wondering if there was a shorthand way of saying "if (x == (any of these))" or if writing them all out was the only option.
谢谢!
推荐答案
谢谢您的问题,现在我找到了一个解决方案一个我敢说),我会用它自己。
Thank you for your question, now as I found a solution (and an elegant one I dare say), I'll use it myself.
与使用std :: find的解决方案不同:a)在编译时被展开为N个比较b)使用任何类型的X可以比较
Unlike solutions with std::find : Will a ) be unrolled to N comparisons in compile time b) work with any types which X can be compared to
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);
}
使用
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;
}
这篇关于检查平等到多种可能性的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!