如何迭代枚举? [英] How can I iterate over an enum?

查看:149
本文介绍了如何迭代枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到你不能在枚举上使用标准的数学运算符,例如++或+ =

I just noticed that you can not use standard math operators on an enum such as ++ or +=

那么最好的方法是迭代所有C ++枚举中的值

So what is the best way to iterate through all of the values in a C++ enum?

推荐答案

典型的方法如下:

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语句中使用它。

This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.

switch ( foo )
{
    case One:
        // ..
        break;
    case Two:  // intentional fall-through
    case Three:
        // ..
        break;
    case Four:
        // ..
        break;
     default:
        assert( ! "Invalid Foo enum value" );
        break;
}

如果你真的想枚举,在一个向量中填充枚举值,结束了。这将正确处理指定的枚举值。

If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.

这篇关于如何迭代枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆