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 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 ... |