检查值是否属于某个静态集的最C ++方法是什么? [英] What's the most C++ way to check if value belongs to certain static set?
问题描述
假设我要编写这样的内容( {1、3、7、42、69、550123}
集在编译前就已经知道):
Let's say that I want to write something like this (the {1, 3, 7, 42, 69, 550123}
set is known before compilation):
int x;
...
if (x == 1 || x == 3 || x == 7 || x == 42 || x == 69 || x == 5550123)
{
...
}
条件看起来很丑,因为我们每个可能的值都有9个额外的符号( || x ==
)。我该如何用更C ++的方式重写它?
The condition looks ugly because we have 9 extra symbols ("|| x ==
") for each possible value. How can I rewrite it in a more C++ way?
我最好的猜测是:
int x;
...
const std::unordered_set<int> v = {1, 3, 7, 42, 69, 5550123};
if (v.count(x))
{
...
}
它的平均复杂度为O(1),有一些内存和时间开销,但看起来仍然很丑。
It has O(1) average complexity with some memory and time overhead, but still looks kinda ugly.
推荐答案
编辑:我刚刚注意到c ++ 14标记。请注意,我的 in
的实现依赖于C ++ 17。也可以使用递归在C ++ 14中完成,但这涉及更多样板,并且编译速度稍慢。
I just noticed c++14 tag. Note that my implementation of in
relies on C++17. It can be done in C++14 as well using recursion, but that involves much more boilerplate, and a bit slower compilation.
一个人可以使用模板来生成一个函数具有逻辑运算符序列,例如nvoigt答案中的一个:
One could use a template to generate a function with a logical operator sequence, such as the one in nvoigt's answer:
template<auto... ts, class T>
constexpr bool
in(const T& t) noexcept(noexcept(((t == ts) || ...))) {
return ((t == ts) || ...);
}
// usage
if (in<1, 3, 7, 42, 69, 5550123>(x))
也就是说,将一组魔术数字隐藏在命名函数的后面可能很有意义:
That said, hiding the set of magic numbers behind a named function probably makes a lot of sense:
constexpr bool
is_magical(int x) noexcept {
return in<1, 3, 7, 42, 69, 5550123>(x);
}
这篇关于检查值是否属于某个静态集的最C ++方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!