以下代码:
enum Type {Prince, Princess, King, Queen, NumTypes};
enum Country {England, Belgium, Netherlands, NumCountries};
class Factory {
static const std::array<std::array<int, NumTypes>, NumCountries> probabilities;
static std::array<std::array<int, NumTypes>, NumCountries> initializeProbabilities() {
std::array<std::array<int, NumTypes>, NumCountries> p;
p[England] = {29, 60, 80, 100};
p[Belgium] = {31, 66, 81, 100};
p[Netherlands] = {25, 45, 90, 100};
return p;
}
};
const std::array<std::array<int, NumTypes>, NumCountries> Factory::probabilities = initializeProbabilities();
如果我改变了enum Country中元素的顺序,那么是安全的,但是对于枚举类型元素的任何重新排序都不安全。如果不逐一初始化所有12个元素,避免这个问题的最佳方法是什么?
答案 0 :(得分:1)
为了避免依赖订单,你应该写一些类似的东西:
p[England][Prince]=29;
p[England][Princess]=60;
p[England][King]=80;
p[England][Queen]=100;
p[Belgium][Prince]=31;
p[Belgium][Princess]=66;
p[Belgium][King]=81;
p[Belgium][Queen]=100;
答案 1 :(得分:0)
这是Brian建议的解决方案(我认为这就是他的意思)。这可能是解决所述问题的最佳方法吗?
enum Type {Prince, Princess, King, Queen, NumTypes};
enum Country {England, Belgium, Netherlands, NumCountries};
class Factory {
static const std::array<std::map<Type, int>, NumCountries> probabilities;
static std::array<std::map<Type, int>, NumCountries> initializeProbabilities() {
std::array<std::map<Type, int>, NumCountries> p;
p[England] = { {Prince, 29}, {Princess, 60}, {King, 80}, {Queen, 100} };
p[Belgium] = { {Prince, 31}, {Princess, 66}, {King, 81}, {Queen, 100} };
p[Netherlands] = { {Prince, 25}, {Princess, 45}, {King, 90}, {Queen, 100} };
return p;
}
};
const std::array<std::map<Type, int>, NumCountries> Factory::probabilities = initializeProbabilities();
或许他的意思是地图的地图。