tags:

views:

82

answers:

3

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_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.

+1  A: 

Unfortunately, C++ does not provide a way to iterate through enums like you want.

Lima Beans
+1  A: 

I have two suggestions:

  1. Use a std::vector to contain the enums.
  2. 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).

Thomas Matthews
+3  A: 

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

tjgreen
+1: you beat me to it by 40 seconds.
Jerry Coffin
Yes, until you need to change file number 54 permanently. Now, how easy is it to count 54 elements over in a list of 324? I prefer the higher-level constructs for readability and such. To each his own :)
San Jacinto
May I suppose that you use a macro for the size because you want C-compatible code ? In C++ it's certainly unnecessary.
Matthieu M.