3 回答

TA貢獻1864條經(jīng)驗 獲得超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;}
如果你真的想要枚舉,將枚舉值填入向量中并迭代它。這也將適當?shù)靥幚碇付ǖ拿杜e值。

TA貢獻1853條經(jīng)驗 獲得超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條經(jīng)驗 獲得超13個贊
如果你的枚舉以0開頭,則增量始終為1。
enum enumType { A = 0, B, C, enumTypeEnd};for(int i=0; i<enumTypeEnd; i++){ enumType eCurrent = (enumType) i; }
如果不是,我想唯一的原因就是創(chuàng)造類似的東西
vector<enumType> vEnums;
添加項目,并使用普通迭代器....
- 3 回答
- 0 關注
- 633 瀏覽
添加回答
舉報