Search code examples
c++multidimensional-arraybada

C++ Array of Variable sized Arrays


I am very new to C++ and I realise the following is not necessarily as easy as I'd like it to be, but I'd really appreciate a more expert opinion.

I am essentially trying to achieve a dynamic iteration over a variable sized array of variable sized arrays similar to the following.

String *2d_array[][] = {{"A1","A2"},{"B1","B2","B3"},{"C1"}};

for (int i=0; i<2d_array.length; i++) {
    for (int j=0; j<2d_array[i].length; j++) {
         print(2d_array[i][j]);
    }
}

Is there a reasonable way to do this? Perhaps by using a vector, or another struct?

Thanks :)


Solution

  • You are using a plain C array of C++ string objects. In C there are no variable sized arrays. Besides that this code wont compile anyway, in such a construct the compiler will generate a array of arrays that have the maximum length declared. In the sample case that would be

    String *2d_array[3][3] 
    

    If you want variable sized arrays, you have to use C++ STL(Standard template library)-containers such as vector or list:

    #include <string>
    #include <vector>
    
    void f()
    
    {
        typedef std::vector<std::string>   CStringVector;
        typedef std::vector<CStringVector> C2DArrayType;
        C2DArrayType theArray;
    
        CStringVector tmp;
        tmp.push_back("A1");
        tmp.push_back("A2");
        theArray.push_back(tmp);
    
        tmp.clear();
        tmp.push_back("B1");
        tmp.push_back("B2");
        tmp.push_back("B3");
        theArray.push_back(tmp);
    
        tmp.clear();
        tmp.push_back("C1");
        theArray.push_back(tmp);
    
        for(C2DArrayType::iterator it1 = theArray.begin(); it1 != theArray.end(); it1++)
            for(CStringVector::iterator it2 = it1->begin(); it2 != it1->end(); it2++)
            {
                std::string &s = *it2;
            }
    }