how to create a contiguous 2d array in c++?

后端 未结 7 1500
走了就别回头了
走了就别回头了 2020-11-21 23:52

I want to create a function that returns a contiguous 2D array in C++.

It is not a problem to create the array using the command:

 int (*v)[cols] = n         


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 00:45

    Unless the size of the two dimensions is known at compile time, your don't have much choice: allocate a single rows*cols array of ints, and roll your own 2D indexing with integer multiplication and addition. Wrapping this in a class can produce a nice-looking syntax for accessing array elements with square bracket operator. Since your array is 2D, you will need to use proxy (AKA "surrogate") objects for the first level of data access.

    Here is a small sample code that uses std::vector for maintaining a contiguous memory region in dynamic memory:

    template
    class Array2D {
        vector data;
        size_t cols;
    public:
        // This is the surrogate object for the second-level indexing
        template 
        class Array2DIndexer {
            size_t offset;
            vector &data;
        public:
            Array2DIndexer(size_t o, vector &dt) : offset(o), data(dt) {}
            // Second-level indexing is done in this function
            T& operator[](size_t index) {
                return data[offset+index];
            }
        };
        Array2D(size_t r, size_t c) : data (r*c), cols(c) {}
        // First-level indexing is done in this function.
        Array2DIndexer operator[](size_t index) {
            return Array2DIndexer(index*cols, data);
        }
    };
    

    You can now use Array2D as if it were a built-in C++ array:

    Array2D a2d(10, 20);
    for (int r = 0 ; r != 10 ; r++) {
        for (int c = 0 ; c != 20 ; c++) {
            a2d[r][c] = r+2*c+1;
        }
    }
    

    Running demo on ideone.

提交回复
热议问题