为了账号安全,请及时绑定邮箱和手机立即绑定

我如何迭代枚举?

我如何迭代枚举?

C++
温温酱 2019-08-01 14:15:06
我如何迭代枚举?我只是注意到你不能在枚举上使用标准数学运算符,如++或+ =那么迭代C ++枚举中所有值的最佳方法是什么?
查看完整描述

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

如果你真的想要枚举,将枚举值填入向量中并迭代它。这也将适当地处理指定的枚举值。


查看完整回答
反对 回复 2019-08-01
?
慕容森

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;

}


查看完整回答
反对 回复 2019-08-01
?
红颜莎娜

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;

添加项目,并使用普通迭代器....


查看完整回答
反对 回复 2019-08-01
  • 3 回答
  • 0 关注
  • 605 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号