Domanda

I have an enum and I want to put them all in the set( and then remove some with set_intersection algorithm, but that is offtopic). All works great except Im stuck on step 1. :)

If I have(real class has enum with higher cardinality)

class MyClass
{
enum Color{red, green , blue}
};

How would I init a std::set<MyClass::Color> to contain all enums.
I can obviously manually insert them one by one, do a for loop with casting since they are consecutive and start from 0 (I think that is required if I dont use = in enum definition), but Im looking for a more elegant way.

EDIT: I prefer C++03 solution if possible because current instance of problem requires it, but if not C++11 is good to know too.

È stato utile?

Soluzione

This is an option:

#define COLORS {red, green , blue}
enum Color COLORS;
static std::set<Color> color_set() {
    return COLORS;
}
#undef COLORS

Altri suggerimenti

Use a std::bitset< total_colors >. That is a more appropriate data structure for a set over a finite space. Each color maps to a Boolean value, representing whether or not it is part of the set. You can initialize it to all true's using my_bitset.set().

Personally I'd use a loop, and just cast the things as I go.

However, if you're dead set against casts you could define operators on the enum so you can iterate over them using ++. That way you can loop without casting.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top