I have been getting back into C++ today, after a few years of Python and R. I am completely rusty, but decided to create a matrix object to re-familiarise. In reality I wouldn't use this class, since I know Boost has matrix objects, but it's good practice!
It can be compiled with g++ -std=c++11 matrix.cpp -o m.
Any thoughts or comments are most welcome.
#include <iostream>
#include <vector>
class matrix {
// Class: matrix
//
// Definition:
// creates a 2d - matrix object as a vector of vectors and
// populates with (int) zeros.
//
// Methods: get_value, assign_value, get_row.
// create vector of vectors
std::vector<std::vector<int> > m;
public:
// constructor for class, matrix dimension (rows=X, cols=Y).
matrix( int X, int Y) {
m.resize(X, std::vector<int>(Y, 0));
}
class row {
//class for matrix row object. Pass in a
// vector and overload `[]`.
std::vector<int> _row;
public:
// constructor
row(std::vector<int> r) : _row(r) {
}
// overload `[]` to return y element.
// note `.at()` does a range check and will throw an error
// if out of range
int operator[]( int y) {
return _row.at(y);
}
};
// overload [] to return x element
row operator[]( int x) {
return row(m.at(x));
}
int get_value ( int x, int y ) {
// Function: get_value
// Definition: returns value `v` of element
// `xy` in matrix `M`.
return m[x][y];
}
void assign_value ( int x, int y, int v ) {
// Function: assign_value
// Definition: Assigns value `v` to element
// `xy` in matrix.
m[x][y] = v;
}
std::vector<int> get_row(int y, int X){
// Function get_row
// Definition: returns a vector object with row
// of x-values of length X at y.
std::vector<int> ROW;
for ( int i=y; i<=y;i++){
for (int j=0; j<=X-1;j++){
ROW.push_back(m[i][j]);
}
}
return ROW;
}
};
int main(){
// specify matrix dimensions
int N = 10; // number of rows
int M = 10; // number of cols
// create a matrix object
matrix mm(N,M);
// print elements
int i, j;
for (i=0; i<=N-1;i++){
for (j=0;j<=M-1; j++){
std::cout << mm[i][j];
}
std::cout << std::endl;
}
// grab a value and print it to console
std::cout << mm.get_value(0,0) << std::endl;
// assign a new value (v = 1) to element (0,0)
mm.assign_value(0,0,1);
// re-print the updated matrix
for (i=0; i<=N-1;i++){
for (j=0;j<=M-1; j++){
std::cout << mm[i][j];
}
std::cout << std::endl;
}
// `get_row()` test
std::vector<int> R = mm.get_row(0, M);
for( int i: R){
std::cout << i << ' ';
}
}