Best way of constructing matrices in C++
19:34 27 Feb 2024

I think there is no other discussion which answers precisely my question.

In C language I construct 2D arrays (with number of rows and columns possibly defined on the run) with pointers of pointers and dynamical memory allocation. Now in C++ I'm deciding if it is better to use standard vectors (of vectors) or continue to use pointers. I read that with standard vectors (of vectors) the memory for the components is not allocated sequentally. Is it true? If it is so this is enough for me to continue to use pointers for now, unless you give me some other definitely good reason not to do it.

The pointers I construct are the following (I didn't study classes yet):

template 
T **Mat(int r, int c)
{
    T** A = (T**)malloc(r * sizeof(T*));
    T* p = (T*)malloc(r * (c * sizeof(T)));
    if (p == NULL || A == NULL) {
        std::cout << "Memory not allocated";
    }
    for (int i = 0; i < r; i++, p += c) A[i] = p;
    return A;
}

template 
void freeMat(T **A)
{
    free(A[0]); free(A);
}
c++ arrays matrix