Monday, August 1, 2016

C++ Matrix

Then after array, there's matrix. Matrix / matrices is used most on spatial problem, there's also 3D matrix and the concept is the same

here's how you create a matrix
int row, column = 2;
int** matrix = new int *[row];
for (int i = 0; i < row; i++) {
  matrix[i] = new int[column];
}
basically you create arrays within array, first we create an array that holds the rows, and then we create arrays within those rows which makes accessing column 4 and row 2 is put as matrix[2][4] here's the complete codes
#include 
#include 

using namespace std; 

int main() {
  // ask for input
  int column, row;
  cout << "Please insert number of column and rows separated by space, ex : \"4 2\"" << endl;
  cin >> column >> row;

  // set the matrix
  int** matrix = new int *[row];
  for (int i = 0; i < row; i++) {
    matrix[i] = new int[column];
  }

  // set the value
  int k = 0;
  for (int i = 0; i < row; i++) {
    for (int j = 0; j < column; j++) {
      matrix[i][j] = k;
      k++;
    }
  }

  // print sample
  for (int i = 0; i < row; i++) {
    for (int j = 0; j < column; j++) {
      cout << matrix[i][j] << " ";
    }
    cout << endl;
  }

  // delete the matrix
  for (int i = 0; i < row; i++) {
    delete matrix[i];
  }
  delete matrix;
}
as for deleting, you need to delete the columns first then delete the rows. should you delete the rows directly then all the columns array will still exists and cannot be used by other process.

No comments :

Post a Comment