0

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.

s73v3r
  • 1,751
  • 2
  • 22
  • 48
  • possible duplicate of [C++: Iterate through an enum](http://stackoverflow.com/questions/261963/c-iterate-through-an-enum) – Joe Sep 04 '10 at 02:18
  • Some good stuff in the duplicate post. – Joe Sep 04 '10 at 02:18

4 Answers4

5

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

Lima Beans
  • 292
  • 2
  • 11
4

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
  • 469
  • 2
  • 10
  • 1
    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 Sep 03 '10 at 23:07
  • 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. Sep 04 '10 at 16:06
1

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
  • 56,849
  • 17
  • 98
  • 154
0

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.

Laurens
  • 1
  • 1