Iterate through Enums in C++
C++ enum question.
So I have a list of files, and their IDs that I need to iterate over, and do stuff to. Most of the stuff is the same, but there are a few file-specific things that need to be done. I tried putting the file IDs in an enum, and iterating over that. Howver, the fileIDs are non contiguous, and jump around.
Currently, I have something akin to this
for(int i = 0; i < FILE_ENUM_MAX; i++)
{
currentFile = myEnum(i);
// do stuff
}
enum myEnum {
file1 = 0x1111,
file2 = 0x8000,
file3 = 0x75,
file4 = 0x120,
FILE_ENUM开发者_StackOverflow中文版_MAX = 4
}
This doesn't work; I just go through files 0, 1, 2, and 3. I get the idea that I can't just get the Nth item in an enumeration by asking for item N. So what would be the best way to iterate over this enum? Or should I just get rid of it? I probably could put the items in numerical order, but I'd prefer a solution to where order didn't matter.
Unfortunately, C++ does not provide a way to iterate through enums like you want.
I guess the low-tech answer might be to skip the enum, and just create a static array:
#define ARRAYSIZE(a) (sizeof(a)/sizeof(a[0]))
int FILE_ENUM[] = { 0x1111, 0x8000, 0x75, 0x120 };
for(int i = 0; i < ARRAYSIZE(FILE_ENUM); i++) {
currentFile = myEnum[i];
// do stuff
}
TJ
I have two suggestions:
- Use a
std::vector
to contain the enums. - Use a
std::map
to contain the enums.
Solution 2 offers a benefit where the key is the file ID and the value can be the name of the file (or an object containing attributes of the file, such as a file handle or pointer).
i <= FILE_ENUM_MAX and it will iterate with 4th file. Sorry if this is an old thread but maybe someone will still need an answer trying to find it here.
精彩评论