C++ 中的枚举中的数组
Arrays in enums in C++
目前我的C++代码是:
constexpr struct my_codes {
std::array<int, other_class1::static_constans1> num1 = {{0, 1, 2, 3, 4, 5, 6}};
std::array<int, other_class2::staric_constans2> num2 = {{7, 8, 9, 10, 11, 12, 13, 14}};
int num3 = 15;
} my_codes;
显然我对此感觉很糟糕,而且它正在失控(我打出了前 100 个数字)。可悲的是,这些枚举是非法的:
enum my_codes {
num1[other_class1::static_constans1],
num2[other_class2::staric_constans2],
num3
};
enum my_codes {num1[7], num2[8], num3};
我可以通过某种魔法在枚举中拥有数组吗?我可以使用任何宏吗?一些递归模板?
编辑:我会像这样使用它:
enum my_codes {num1[7], num2[8], num[3]};
if (some_int == my_codes::num2[3]) do_somethig();
枚举将具有以下值:
my_codes::num1[0] == 0
my_codes::num1[1] == 1
...
my_codes::num1[6] == 6
my_codes::num2[0] == 7
my_codes::num2[1] == 8
...
my_codes::num2[7] == 14
my_codes::num3 == 15
由于常量是连续的,因此不需要数组 - 范围检查操作就足够了。也就是说,由于num1
包含[0, 7)
而num2
包含[7, 15)
,因此您的结构可以表示为
constexpr struct my_codes {
std::array<int,4> num = {{0,7,14,15}}
} mycodes;
constexpr int getIndex(int i, int offset = 0) {
return (offset==3 || i < mycodes.num[offset+1]) ?
offset :
getIndex(i, offset+1) ;
}
这只是通过constexpr
数组编写线性搜索的一种递归方式。生成第 i 个范围更简单,只需num[i]
到 num[i+1]
.
相关文章:
- 带有枚举方向/类型的气泡排序结构数组
- C++ 指向枚举数组的指针
- 生成整数长度的枚举数组
- C++如何将字符串数组中的一个点设置为枚举变量
- 如何从枚举类值中指定模板函数参数中的数组大小?
- 初始化枚举类 (C++11) 类型的二维 std::数组
- 如何递归枚举每个元素都有上限的所有可能的数组
- 从数组中删除枚举并计算总和
- 如何有效地用枚举填充 2D std::数组
- 数组枚举和输入
- 随机生成一个没有重复元素的枚举数组 (C++)
- 地址数组,带有枚举的返回值
- 错误:数组大小表达式必须具有整型或无作用域枚举类型,而不是'double'
- C++ 中的枚举中的数组
- 枚举与数组
- 枚举数组相对于常量和宏的优势
- 传递枚举数组是什么意思
- 枚举数组错误之前的预期主表达式
- 如何使用枚举初始化向量/数组
- 使用固定值枚举数的枚举零初始化