3D array C++ using int [] operator

后端 未结 7 1875
长发绾君心
长发绾君心 2020-12-15 09:03

I\'m new to C/C++ and I\'ve been cracking my head but still got no idea how to make an \"structure\" like this

\

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 09:25

    // one-liner
    typedef std::vector > > ThreeDimensions;
    // expanded
    typedef std::vector OneDimension;
    typedef std::vector TwoDimensions;
    typedef std::vector ThreeDimensions;
    

    (this is tagged c++, after all)

    EDIT in response to Joe's question

    hello again Joe =) sure. here's the example:

    #include 
    #include 
    
    int main(int argc, char* const argv[]) {
    
        /* one-liner */
        typedef std::vector > >ThreeDimensions;
        /* expanded */
        typedef std::vectorOneDimension;
        typedef std::vectorTwoDimensions;
        typedef std::vectorThreeDimensions;
    
        /*
           create 3 * 10 * 25 array filled with '12'
         */
        const size_t NElements1(25);
        const size_t NElements2(10);
        const size_t NElements3(3);
        const int InitialValueForAllEntries(12);
    
        ThreeDimensions three_dim(NElements3, TwoDimensions(NElements2, OneDimension(NElements1, InitialValueForAllEntries)));
    
        /* the easiest way to assign a value is to use the subscript operator */
        three_dim[0][0][0] = 11;
        /* now read the value: */
        std::cout << "It should be 11: " << three_dim[0][0][0] << "\n";
        /* every other value should be 12: */
        std::cout << "It should be 12: " << three_dim[0][1][0] << "\n";
    
        /* get a reference to a 2d vector: */
        TwoDimensions& two_dim(three_dim[1]);
    
        /* assignment */
        two_dim[2][4] = -1;
        /* read it: */
        std::cout << "It should be -1: " << two_dim[2][4] << "\n";
    
        /* get a reference to a 1d vector: */
        OneDimension& one_dim(two_dim[2]);
    
        /* read it (this is two_dim[2][4], aka three_dim[1][2][4]): */
        std::cout << "It should be -1: " << one_dim[4] << "\n";
        /* you can also use at(size_t): */
        std::cout << "It should be 12: " << one_dim.at(5) << "\n";
    
        return 0;
    }
    

提交回复
热议问题