本文介绍了如何优雅地将所有枚举放入std :: set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举,我想把它们所有的集合(然后删除一些与set_intersection算法,但这是offtopic)。
除了我坚持在步骤1之外,所有的工作都很好。)

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}
};

我如何初始化 std :: set< MyClass :: Color> 包含所有枚举。

我可以明显手动插入它们一个,做一个for循环,因为它们是连续的,从0开始(我认为这是必需的if我不使用=在枚举定义),但我寻找一个更优雅的方式。

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.

编辑:我更喜欢C ++ 03解决方案,如果可能的话,因为当前的问题实例需要它,但如果不是C ++ 11也很好知道。

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

推荐答案

这是一个选项:

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

这篇关于如何优雅地将所有枚举放入std :: set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:53