我正在谷歌搜索如何迭代枚举,我发现了各种各样的建议,如 How can I iterate over an enum? 虽然没关系,但所有这些方法都必须重新迭代整数,我发现建议的解决方案或多或少都是一种黑客行为。有没有更深层次的理由为什么不能更好地支持这项操作;或者从另一方面看哪一个更便携(包括C和C ++之间的一个)和更多的标准证明?
答案 0 :(得分:3)
To iterate over a generic enum, portably between C and C++, simply use look-up tables:
typedef enum
{
hello = 123,
world = 456
} hello_t;
const hello_t TABLE [ENUM_ITEMS] =
{
hello,
world
};
for(size_t i=0; i<ENUM_ITEMS; i++)
{
printf("%d", (int)TABLE[i]);
}
Unfortunately there is no way to programatically get the constant ENUM_ITEMS
, unless you have a non-specific enum with no values assigned, like enum { hello, world, ENUM_ITEMS }
. If some enumeration constants are explicitly assigned numbers, then you can only do something hack-ish like this:
typedef enum
{
ENUM_START = __LINE__,
hello = 123,
world = 456,
ENUM_ITEMS = __LINE__ - ENUM_START - 1
} hello_t;
答案 1 :(得分:1)
C or C++ ? It's not the same thing.
You can't iterate over enum in C, because enum is just switched by there number at the compilation time. however, if your sure of what's inside your enum, you can "iterate", like that :
enum color {
YELLOW,
GREEN,
BLUE,
RED,
/* Please, add new color BEFORE this comment */
NB_COLOR
};
for (int i = 0; i < NB_COLOR; ++i) {
/* Do something */
}
But it's more like a hack as you say it, because you can't be sure that your enum start with 0 and you can't be sure that there is not "empty slot" between enum in C.