A good way to create a dynamic 2D matrix in C ++ 11

I already know how to create a dynamic 2D matrix with newand free it with delete. Since C ++ 11 has many new memory functions here, such as unique_ptr, arraycontainer, etc .; what is a good way to create a 2D matrix, so you don’t need to explicitly release the matrix using an operator delete?

+4
source share
3 answers

One of the simplest ways is to use vector vectors

const int N = 10;
const int M = 10;
vector<vector<int>> matrix2d(N, vector<int>(M, 0)); // 10x10 zero-initialized matrix
matrix2d[0][0] = 42;

Of course you can use one vector and transfer it to the accessor class

vector<int> matrix(N * M, 0) // Ditto as above, but needs stride-aware accessors

I will give a small example here for completeness.

template <typename T>
class Matrix2D {
    std::vector<T> data;
    unsigned int sizeX, sizeY;
public:
    Matrix2D (unsigned int x, unsigned int y)
        : sizeX (x), sizeY (y) {
        data.resize (sizeX*sizeY);
    }

    T& operator()(unsigned int x, unsigned int y) {
        if (x >= sizeX || y>= sizeY)
            throw std::out_of_range("OOB access"); // Throw something more appropriate
        return data[sizeX*y + x]; // Stride-aware access
    }
};

, , . , vector<vector<int>> , , , , .

+3

array_view GSL, .

#include <array>
#include <vector>
#include "array_view.h" // must be manually imported until standardization

int main()
{
    std::array<int, 10>  arr{}; // 10 ints on the stack
    std::vector<int>  vec{12}; // 12 ints on the heap
    auto a = gsl::array_view<int, 2>{{2, 5}, arr}; // 2D, 2x5 matrix
    auto b = gsl::array_view<int, 3>{{3, 2, 2}, vec}; // 3D, 3x2x2 matrix
    auto c = gsl::array_view<int>{vec}; // 1D, spans from `begin()` to `end()`
    a[{0,3}] += b[{0,1,1}] * -c[2]; // access syntax
}

N.B. array_view , . . .

+3

, , ++ 11. .

#include <iostream>
#include <vector>

using namespace std; 

typedef vector<vector<int>> Matrix2D;
typedef vector<Matrix2D> Matrix3D;

Matrix2D my_arr;

int main()
{
    const size_t N = 9;

    for(unsigned s = 4; s <= N; s++)
    {       
        my_arr.resize(s);
        for(unsigned i = 0; i < s; i++)
            my_arr[i].resize(s,s);

        for(unsigned i = 0; i < s; i++)
        {
            for(unsigned j = 0; j < s; j++)
                cout << my_arr[i][j] << " ";
            cout << endl;
        }

        cout << "\n\n";
    }
    return 0;
}
0

Source: https://habr.com/ru/post/1610042/


All Articles