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

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

问题描述

我有一些 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_
};

这样做你可以先授予 &last 从不改变顺序

Doing such you can grant first & last never changes order

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

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