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
这篇关于是否有任何众所周知的迭代枚举值的范例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有任何众所周知的迭代枚举值的范例?
- “纯虚函数调用"在哪里?崩溃从何而来? 2022-10-18
- 使用最流行的转义序列 1970-01-01
- 打印扩展的ASCII字符 1970-01-01
- 使用整数值初始化char类型的变量 1970-01-01
- C语言可使用的所有转义序列 1970-01-01
- C语言求模 1970-01-01
- 运算符优先级 1970-01-01
- 使用来自float.h和limits的数据,找到该系统的一些 1970-01-01
- C++浮点常数 1970-01-01
- C++指向数组的指针 1970-01-01