Initialize a two-dimensional array with different column sizes in c ++

advertisements

This question already has an answer here:

  • Do jagged arrays exist in C/C++? 7 answers

Is there a way to initialize two dimensional array with different size of columns in c++? I try to make console card game. I have done something like this while ago.

 static string const group[7][];

 string const Cards::group = {
            { "AA", "KK", "AKs" },
            { "QQ", "JJ", "AK", "AJs", "KQs", "AQs" },
            { "TT", "AQ", "ATs", "KJs", "QJs", "JTs" },
            { "99", "88", "AJ", "AT", "KQ", "KTs", "QTs", "J9s" , "T9s" , "98s" },
            { "77", "66", "A9s", "A5s", "A4s", "A3s", "A2s", "K9s", "KJ", "KT", "QJ", "QT", "Q9s", "JT", "QJ", "T8s", "97s", "87s", "76s", "65s"},
            { "55", "44", "33", "22", "K9", "J9", "86s"},
            { "T9", "98", "85s"}
    };

It doesn't work. It would be great if an array would be additionally static and constant but it isn't necessary. The most important thing is to make code works.

I would be grateful for any kind of help.


Arrays in C++ are not truly dynamic; they cannot be extended nor reduced in size. Moreover, the dimensions of static arrays have to be known at their declaration. Dynamically-allocated arrays can be used by declaring group as a string** and later initializing it with the appropriately-sized memory. You can also use a 2-dimensional vector which is fundamentally equivalent but preferred because it is cleaner because we can leverage its memory management:

static std::vector<std::vector<std::string>> const group;

std::vector<std::vector<std::string>> Cards::group = {
    { "AA", "KK", "AKs" },
    { "QQ", "JJ", "AK", "AJs", "KQs", "AQs" },
    { "TT", "AQ", "ATs", "KJs", "QJs", "JTs" },
    { "99", "88", "AJ", "AT", "KQ", "KTs", "QTs", "J9s" , "T9s" , "98s" },
    { "77", "66", "A9s", "A5s", "A4s", "A3s", "A2s", "K9s", "KJ", "KT", "QJ", "QT", "Q9s", "JT", "QJ", "T8s", "97s", "87s", "76s", "65s"},
    { "55", "44", "33", "22", "K9", "J9", "86s"},
    { "T9", "98", "85s"}
};