有没有任何众所周知的范例来迭代枚举值? [英] Is there any well-known paradigm for iterating enum values?

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

问题描述

我有一些C ++代码,其中声明了以下枚举:

I have some C++ code, in which the following enum is declared:

enum Some 
{
   Some_Alpha = 0,
   Some_Beta,
   Some_Gamma,
   Some_Total
};
int array[Some_Total];

Alpha,Beta和Gamma的值是连续的,我很乐意使用以下循环

The values of Alpha, Beta and Gamma are sequential, and I gladly use the following cycle to iterate through them:

for ( int someNo = (int)Some_Alpha; someNo < (int)Some_Total; ++someNo ) {}

这个循环是确定的,直到我决定改变枚举的声明顺序,使Beta成为第一个值,Alpha成为第二个值。这使循环头无效,因为现在我必须从Beta迭代到Total。
那么,通过枚举迭代的最佳实践是什么?我想遍历所有的值,而不改变每次循环头。我可以想到一个解决方案:

This cycle is ok, until I decide to change the order of the declarations in the enum, say, making Beta the first value and Alpha - the second one. That invalidates the cycle header, because now I have to iterate from Beta to Total. So, what are the best practices of iterating through enum? I want to iterate through all the values without changing the cycle headers every time. I can think of one solution:

enum Some 
{
   Some_Start = -1,
   Some_Alpha,
   ...
   Some_Total
};
int array[Some_Total];

并从(Start + 1)到Total,但看起来很丑陋,在代码中做它。有没有任何众所周知的范例来迭代枚举,或者我只需要修正枚举值的顺序? (让我们假装,我真的有一些真棒原因改变枚举值的顺序)...

and iterate from (Start + 1) to Total, but it seems ugly and I have never seen someone doing it in the code. Is there any well-known paradigm for iterating through the enum, or I just have to fix the order of the enum values? (let's pretend, I really have some awesome reasons for changing the order of the enum values)...

推荐答案

enum Some
{
   Some_first_ = 0,
   Some_Alpha = Some_first_,
....
   Some_last_
};

上次从未更改订单

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

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