简体   繁体   中英

Initializing static 2D array

This following code:

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();

is safe if I ever change the order of elements in enum Country, but it is not safe from any future reordering of enum Type elements. What is the best way to avoid that problem without initializing all 12 elements one by one?

In order to avoid dependency on the order, you should write something like:

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;

This is the solution suggested by Brian (I think this is what he meant). Is this probably the best way to solve the issues described?

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();

Or perhaps he meant map of a map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM