Home > Backend Development > C++ > How to Create Dynamic Two-Dimensional Arrays in C ?

How to Create Dynamic Two-Dimensional Arrays in C ?

Mary-Kate Olsen
Release: 2024-12-14 18:00:28
Original
126 people have browsed it

How to Create Dynamic Two-Dimensional Arrays in C  ?

Creating Dynamic Two-Dimensional Arrays in C

In C , the traditional method of declaring an array involves specifying its dimensions at compile time. However, what if you need to create an array whose size is determined dynamically based on user input?

Vector of Vectors: vector>

One approach is to use a vector of vectors. A vector> would create a dynamic two-dimensional array, but this can introduce both speed and memory overhead due to the multiple layers of indirection involved.

Custom Matrix Class

For optimal performance, consider creating a custom matrix class:

template <class T>
class matrix {
    int columns_;
    std::vector<T> data;

public:
    matrix(int columns, int rows) : columns_(columns), data(columns * rows) {}

    T& operator()(int column, int row) { return data[row * columns_ + column]; }
};
Copy after login

This class allows you to access matrix elements using a concise operator(), imitating the syntax of a two-dimensional array.

Example Matrix Implementation

For reference, here is a statically allocated 3D matrix implementation using multiple levels of proxies to support operator[] syntax:

template<class T, int size>
class matrix3 {

    T data[size][size][size];

    friend class proxy;
    friend class proxy2;

    class proxy {
        matrix3& m_;
        int index1_, index2_;

    public:
        proxy(matrix3& m, int i1, int i2) : m_(m), index1_(i1), index2_(i2) {}

        T& operator[](int index3) { return m_.data[index1_][index2_][index3]; }
    };

    class proxy2 {
        matrix3& m_;
        int index_;

    public:
        proxy2(matrix3& m, int d) : m_(m), index_(d) {}

        proxy operator[](int index2) { return proxy(m_, index_, index2); }
    };

public:
    proxy2 operator[](int index) { return proxy2(*this, index); }
};
Copy after login

Usage

Both implementations can be used to create and manipulate dynamic two-dimensional arrays with the familiar C syntax.

The above is the detailed content of How to Create Dynamic Two-Dimensional Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template