问题描述
我刚刚注意到您不能在枚举上使用标准数学运算符,例如 ++ 或 +=
I just noticed that you can not use standard math operators on an enum such as ++ or +=
那么遍历 C++ 枚举中的所有值的最佳方法是什么?
So what is the best way to iterate through all of the values in a C++ enum?
推荐答案
典型方式如下:
enum Foo {
One,
Two,
Three,
Last
};
for ( int fooInt = One; fooInt != Last; fooInt++ )
{
Foo foo = static_cast<Foo>(fooInt);
// ...
}
请注意,枚举 Last
旨在被迭代跳过.使用这个假"Last
枚举,您不必在每次要添加新枚举时将 for 循环中的终止条件更新为最后一个真实"枚举.如果您想稍后添加更多枚举,只需将它们添加到 Last 之前.本例中的循环仍然有效.
Please note, the enum Last
is meant to be skipped by the iteration. Utilizing this "fake" Last
enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum.If you want to add more enums later, just add them before Last. The loop in this example will still work.
当然,如果指定了枚举值,这会崩溃:
Of course, this breaks down if the enum values are specified:
enum Foo {
One = 1,
Two = 9,
Three = 4,
Last
};
这说明枚举并不是真的要迭代.处理枚举的典型方法是在 switch 语句中使用它.
This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.
switch ( foo )
{
case One:
// ..
break;
case Two: // intentional fall-through
case Three:
// ..
break;
case Four:
// ..
break;
default:
assert( ! "Invalid Foo enum value" );
break;
}
如果您真的想枚举,请将枚举值填充到向量中并对其进行迭代.这也将正确处理指定的枚举值.
If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
这篇关于如何遍历枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!