C++ 将数字追加到枚举以获取其他枚举
我想在for循环中通过追加一个数字来获取枚举值,如C++ 将数字追加到枚举以获取其他枚举,c++,c++11,enums,enumeration,C++,C++11,Enums,Enumeration,我想在for循环中通过追加一个数字来获取枚举值,如 enum example { Example_1, Example_2, Example_3, . . . Example_n }; example x; for (i = 0; i < n; i++ {x = Example_ + i; // if i = 5, I need Example_5 } enum示例 { 例1:, 例2:, 例3:, . . . 示例 }; 例十; 对于(i=0;i
enum example
{
Example_1,
Example_2,
Example_3,
.
.
.
Example_n
};
example x;
for (i = 0; i < n; i++
{x = Example_ + i; // if i = 5, I need Example_5
}
enum示例
{
例1:,
例2:,
例3:,
.
.
.
示例
};
例十;
对于(i=0;i
我希望在C++11中实现这个函数如果枚举中有一个
Example\u 0
,那么Example\u 0+5
将为您提供一个与Example\u 5
等价的整数值。枚举就是整数
所有这一切都假设您没有显式地为某个枚举常量指定一个值—这是另一回事。您不能将名称与数字连接起来以检索枚举名称并使用枚举值
- 对于连续枚举,可以使用简单的算术运算
- 您可以为枚举创建
,通过开关解析:operator++
因此,可能example operator++(example e) { switch (e) { case Example_1: return Example_2; case Example_2: return Example_3; case Example_3: return Example_4; // ... case Example_n: return Last; }; throw std::runtime("value out of range"); }
例如(例如e=example_1:e!=Last;++e){/*..*/}
- 使用数组提供枚举列表:
允许:constexpr auto AllExamples() { constexpr std::array res{{Example_1, Example_2, /*..*/, Example_n}}; return res; }
for (auto ex : AllExamples()) {/*..*/} f(AllExamples()[5]);
- 如果你真的要玩名字,也可以使用地图:
std::map<std::string, example> ExamplesAsMap() { return { {"Example_1", Example_1}, {"Example_2", Example_2}, /*..*/ {"Example_n", Example_n}, {"Value_1", Value_1}, {"Value_2", Value_2}, /*..*/ {"Value_n", Value_n} /**/ }; }
然后std::map examplesamap(){ 返回{ {“示例1”,示例1}, {“示例2”,示例2}, /*..*/ {“示例”,示例}, {“Value_1”,Value_1}, {“Value_2”,Value_2}, /*..*/ {“Value\u n”,Value\u n} /**/ }; }
const auto m = ExamplesAsMap(); example x; for (int i = 0; i < n; i++) { x = m.at("Example_" + std::to_string(i)); // ... }
const auto m=examplesamap(); 例十; 对于(int i=0;i