What Is the Best Modern C++ Approach to Construct and Manipulate a 2D Array

what is the best modern c++ approach to construct and manipulate a 2d array

I happen to have this completely untested example lying around. If it works, good, otherwise it is an example of how you might go about creating a 2D view onto a 1D array:

template<typename T>
class two_dee_array
{
public:
two_dee_array(std::size_t row, std::size_t col)
: v(row * col), stride(col) {}

T& operator()(std::size_t row, std::size_t col)
{ return v[(row * stride) + col]; }

T const& operator()(std::size_t row, std::size_t col) const
{ return v[(row * stride) + col]; }

std::size_t col_size() const { return stride; }
std::size_t row_size() const { return v.size() / stride; }

auto begin() { return std::begin(v); }
auto end() { return std::end(v); }

auto begin() const { return std::begin(v); }
auto end() const { return std::end(v); }

auto cbegin() const { return std::cbegin(v); }
auto cend() const { return std::cend(v); }

private:
std::vector<T> v;
std::size_t stride;
};

Statically declared 2-D array C++ as data member of a class

class Array2D {
public:
vector<int> v;
int nc;
Array2D(int NR, int NC) : v(NR*NC), nc(NC) {}
int* operator[](int r) { return &v[r*nc]; }
};

int main()
{
Array2D array2d(2, 3);
array2d[0][0] = 1;
array2d[1][2] = 6;
}

This allows you to create a class that will function like a 2D array. It's fast and the data is contiguous.

How do I declare a 2d array in C++ using new?

If your row length is a compile time constant, C++11 allows

auto arr2d = new int [nrows][CONSTANT];

See this answer. Compilers like gcc that allow variable-length arrays as an extension to C++ can use new as shown here to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.

Another efficient option is to do the 2d indexing manually into a big 1d array, as another answer shows, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap).


Otherwise, you can use an array of pointers to arrays to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this:

int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];

The above, for colCount= 5 and rowCount = 4, would produce the following:

Sample Image

Don't forget to delete each row separately with a loop, before deleting the array of pointers. Example in another answer.

C++, How to make a dynamically sized 2D array in object oriented programming?

This loop is wrong.

for (int j = 0; j < this->length; i++) {

You have to increment j, not i.

How to define a 2D array in C++ and STL without memory manipulation?

are there other ways to define the 2D array?

No without manipulating memory explicitely (malloc/free). If you use static allocated array (1st example) you allocate the space at compile time, so you can't add more rows or columns at runtime.

The second example uses std::vector that hides to you dynamic memory allocation . This way you can eventually add more rows or columns at runtime.

If you don't need to dynamically modify the array dimension, then the first solution is the simpler and faster one (even if I think that std::vector implementation is fast enough to be comparable to static array, more elegant and more object oriented).

If you need to modify the array dimension at run-time use std::vector, because it saves you from dealing directly with malloc and free.

manipulating multidimensional arrays with functions in C++

Arrays are not passed by value, so you can simply use

void func(int mat[][3])

and, if you modify the values of mat inside func you are actually modifying it in main.

You can use that approach if you know a priori the size of your matrix, otherwise consider working with pointers:

#include <iostream>

void f(int **m, int r, int c) {
m[0][0]=1;
}

int main () {

int **m;
int r=10,c=10;
int i;

m = (int**)malloc(r*sizeof(int*));

for (i=0; i<r;i++)
m[i] = (int*)malloc(c*sizeof(int));

f(m,r,c);

printf("%d\n",m[0][0]);

for(i=0;i<r;i++)
free(m[i]);

free(m);

return 0;

}

Passing a 2D array to a C++ function

There are three ways to pass a 2D array to a function:

  1. The parameter is a 2D array

    int array[10][10];
    void passFunc(int a[][10])
    {
    // ...
    }
    passFunc(array);
  2. The parameter is an array containing pointers

    int *array[10];
    for(int i = 0; i < 10; i++)
    array[i] = new int[10];
    void passFunc(int *a[10]) //Array containing pointers
    {
    // ...
    }
    passFunc(array);
  3. The parameter is a pointer to a pointer

    int **array;
    array = new int *[10];
    for(int i = 0; i <10; i++)
    array[i] = new int[10];
    void passFunc(int **a)
    {
    // ...
    }
    passFunc(array);


Related Topics



Leave a reply



Submit