How to elegantly put all enums into a std::set

杀马特。学长 韩版系。学妹 提交于 2019-12-05 01:46:44

问题


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.


回答1:


This is an option:

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



回答2:


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().




回答3:


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.



来源:https://stackoverflow.com/questions/15411519/how-to-elegantly-put-all-enums-into-a-stdset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!