3 回答

TA贡献1864条经验 获得超6个赞
典型的方法如下:
enum Foo { One, Two, Three, Last};for ( int fooInt = One; fooInt != Last; fooInt++ ){ Foo foo = static_cast<Foo>(fooInt); // ...}
当然,如果指定了枚举值,这会分解:
enum Foo { One = 1, Two = 9, Three = 4, Last};
这说明枚举并不是真正意义上的迭代。处理枚举的典型方法是在switch语句中使用它。
switch ( foo ){ case One: // .. break; case Two: // intentional fall-through case Three: // .. break; case Four: // .. break; default: assert( ! "Invalid Foo enum value" ); break;}
如果你真的想要枚举,将枚举值填入向量中并迭代它。这也将适当地处理指定的枚举值。

TA贡献1853条经验 获得超18个赞
#include <iostream>
#include <algorithm>
namespace MyEnum
{
enum Type
{
a = 100,
b = 220,
c = -1
};
static const Type All[] = { a, b, c };
}
void fun( const MyEnum::Type e )
{
std::cout << e << std::endl;
}
int main()
{
// all
for ( const auto e : MyEnum::All )
fun( e );
// some
for ( const auto e : { MyEnum::a, MyEnum::b } )
fun( e );
// all
std::for_each( std::begin( MyEnum::All ), std::end( MyEnum::All ), fun );
return 0;
}

TA贡献1842条经验 获得超12个赞
如果你的枚举以0开头,则增量始终为1。
enum enumType { A = 0, B, C, enumTypeEnd};for(int i=0; i<enumTypeEnd; i++){ enumType eCurrent = (enumType) i; }
如果不是,我想唯一的原因就是创造类似的东西
vector<enumType> vEnums;
添加项目,并使用普通迭代器....
- 3 回答
- 0 关注
- 605 浏览
添加回答
举报