C/C++ Code Snippets

This section provides some code snippets to solve some common problems in both elegant and efficient way:


2-Dimensional arrays with dynamic size in C [click to open/close section]

A common problem in C is representing 2 (or more) dimension arrays in an efficient way (avoiding memory fragmentation) and easy to use (with direct indexing, i.e. A[i][j]) when the size is not known at compile time, a solution to the problem is provided by the following method:

// Creates a 2-dimensional array of size NxM
double** create_matrix(int N, int M){
   int i;
   double **matrix = (double**) malloc(sizeof(double*) * N); // create an index array
   matrix[0] = (double*) malloc(sizeof(double) * N * M);     // create the array in a contiguous block of memory 
                                                             // (efficient allocation)
   #pragma omp parallel for
   for(i=1; i<N; i++) 
      matrix[i] = matrix[0]+i*M; // element i of the index array points to row i
   return ret;
}

void free_matrix(double** m){
   free(m[0]); // free the main 2D array
   free(m);    // free the indexes array
}

The create_matrix function can be used in the following way:

double** m = create_matrix(100, 50);
m[0][0] = 10;
...
free_matrix(m);
C++ matrix<T> data type [click to open/close section]

A simple data type to represent matrices in C++.

#include 
#include 

template <class T>
class matrix{
   T*       _data;
   size_t   _rows;
   size_t   _cols;
public:
   typedef T        value_type;
   typedef T*       iterator;
   typedef T const* const_iterator;

   matrix(size_t rows, size_t cols): _data(new T[rows*cols]), _rows(rows), _cols(cols){}

   T& operator()(size_t i, size_t j){
      assert(i<_rows && j<_cols);
      return _data[i*_cols+j];
   }
   size_t rows(){ return _rows; }
   size_t cols(){ return _cols; }
   T* begin(){ return &_data[0]; }
   T const* begin() const { return &_data[0]; }
   T* end(){ return &_data[_cols*_rows]; }
   T const* end() const { return &_data[_cols*_rows]; }
   ~matrix(){ delete[] _data; }
};

Usage example:

#include "matrix.hpp"
...
matrix<double> m(100, 50); // create the matrix
std::fill(m.begin(), m.end(), 0.5); // initialize the entire matrix with value 0.5
m(50,25) = 1; // set matrix value to 1
...