Is there any well-known paradigm for iterating enum values?(是否有任何众所周知的迭代枚举值的范例?)
问题描述
我有一些 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
这篇关于是否有任何众所周知的迭代枚举值的范例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有任何众所周知的迭代枚举值的范例?
基础教程推荐
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++ #define 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- 使用scanf()读取字符串 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C语言访问数组元素 1970-01-01
- C++定义类对象 1970-01-01
- C++按值调用 1970-01-01