Here is a my own Matrix class:
class Matrix {
private:
int row; // rows
int col; // columns
double** matrix; // pointer to this matrix
public:
Matrix();
Matrix(int row, int col);//creating matrix based on two params
Matrix(double** matx, int row, int col); //Here is a problem
Matrix(Matrix& N);//copy constructor
~Matrix();
//first, second and fourth constructors works good
int getRow();
int getCol();
void changeSize(int row, int col);
void randValues();
void writeValues();
};
Here is a body of constructor, This constructor need take a exists matrix as parameter and create a new one based on the matrix provided (it's NOT a copy constructor)
Matrix::Matrix(double** matx, int row, int col){
//allocated memory for new matrix
matrix = new double*[row];
for (int i = 0; i < row; i++){
matrix[i] = new double[col];
}
// //copy values to new matrix
for(int i=0; i<row; i++)
{
for(int k = 0; k < col; k++)
{
matrix[i][k] = matx[i][k];
}
}
};
int main(){
double** test = new double *[5];
for(int i = 0; i < 5; i++){
test[i] = new double;
}
for(int i = 0; i < 5; i++){
for(int k = 0; k < 5; k++){
test[i][k] = 0.11;
cout << test[i][k] << " ";//just for make me sure if is ok
}
cout << "\n";
}
Matrix *matx = new Matrix(test,5,5);
matx->writeValues();
return 0;
}
And when I run a program they write on console lots of zeros values and few garbage and of the end is: Process returned -1073741819 (0xC0000005) execution time : 2.162 s
Related
I have created the class and first constructor, but I don't know how to initialize 2d array to ref as asked in 2, need to do this using dynamic memory allocation.
Create a class named matrix having followed private members:
• int **p;
• int rows;
• int cols;
The class should have the following member functions:
matrix () initializes the 2d array to zero. Assume rows = 2 and cols = 2
matrix (int **ref, int r, int c) initializes the 2d array to ref
MY CODE:
class Matrix
{
private:
int **p;
int rows;
int cols;
public:
// CONSTRUCTORS
Matrix()
{
rows = 2;
cols = 2;
p = new int*[2];
// initialize the array with 2x2 size
for (int i=0; i<2; i++)
{
p[i] = new int[2];
}
// taking input for the array
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
p[i][j] = 0;
}
}
};
Matrix(int **ref, int r, int c)
{
rows = r;
cols = c;
p = new int*[rows];
// initialize the array with 2x2 size
for (int i=0; i<rows; i++)
{
p[i] = new int[cols];
}
// taking input for the array
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
p[i][j] = **ref;
}
}
}
friend ostream& operator << (ostream& output, Matrix& obj)
{
output << obj.rows;
cout << " = ROWS" << endl;
output << obj.cols;
cout << " = columns" << endl;
for (int i=0; i<obj.rows; i++)
{
for(int j=0; j<obj.cols;j++)
{
cout << obj.p[i][j] << " " ;
}
cout << endl;
}
return output;
}
};
int main()
{
Matrix a;
cout << a << endl;
return 0;
}
It seems p[i][j] = **ref; should be p[i][j] = ref[i][j];.
Also you should follow The Rule of Three. In other words, you should declare copy constructor and assignment operator to handle object (including pointers) copying properly.
The task is as follows: Describe the class "matrix of numbers" with component data: the dimensions of the matrix, a pointer to the elements. Overload operations: << (matrix output to the screen), + (addition of matrices), unary ¬– (change the sign of each element), / = (divide each element by a number). I performed it, and performed it correctly, but you need to set the matrix dimension from the keyboard, and as you can see, it is set in advance for me [3] [3]. It sounds pretty simple, but something I'm really dumb. Thanks in advance for your help. Here is the code:
#include "pch.h"
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix()
{
int Table[3][3];
}
int Table[3][3];
void Create()
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
Table[i][j] = 10;
}
};
ostream& operator <<(ostream& t, Matrix a)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
t << a.Table[i][j] << " ";
t << "\n";
}
return t;
}
Matrix& operator /=(Matrix& a, int num)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
a.Table[i][j] /= num;
return a;
}
Matrix& operator -(Matrix& a, int empty)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
a.Table[i][j] = -a.Table[i][j];
return a;
}
Matrix& operator +(Matrix& a, Matrix b)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
a.Table[i][j] += b.Table[i][j];
return a;
}
int main()
{
int u;
setlocale(LC_ALL, "Russian");
Matrix Example;
Example.Create();
Matrix Example1;
Example1.Create();
cout << Example;
cout << Example1;
cout << "Сумма матриц: "<<endl;
cout << Example + Example1;
Example - 1;
Example1 - 1;
cout<< Example + Example1;
cout << "На сколько вы хотите её поделить?\n";
cin >> u;
Example /= u;
Example1 /= u;
cout << Example;
cout << Example1;
}`
You need to dynamically create the matrix.
In order to this you need to use pointers(*). Change int table[3][3]
double table**;
An example of how it could be implemented (note that I use matrix instead of table)
class Matrix {
private:
double** matrix;
int col;
int row;
public:
Matrix(){};
void Create(int row, int col);
};
void Matrix::Create(int row_, int col_){
double val = 0.0;
col = col_; // initalize private members
row = row_;
matrix = new double*[row]; // Create a new array of size row_
for(int i = 0; i < row; i++)
{
matrix[i] = new double[col]; // Create new cols of size col (inside array of row)
}
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
matrix[i][j] = val;
val = val + 1.0;
}
}
}
I tried to reuse your design for simplicity, but I really suggest that you try to specify the dimensions of the matrix in a constructor instead and maybe even construct the matrix in it as well.
Something like this:
Matrix(int row_, int col_) : row(row_), col(col_) {*/ create matrix here /*};
You can skip the "create matrix here" part and use your own Create() if you want to.
You need dynamic memory allocation for that. I won't fiddle around with pointers (new / delete) unless you are explicitly told to. As a beginner you should probably use the standard template library (STL) tools:
#include <vector> and use std::vector<std::vector<int>> Table instead of int Table[3][3]. Then write a constructor like this:
Matrix(std::size_t rows, std::size_t cols)
{
Table.resize(rows);
for (unsigned int i = 0; i < Table.size(); ++i)
Table[i].resize(cols);
}
You can additionally store the dimension of the matrix, but there is no need to do it since you can get the information from the vectors. Replace the hardcoded dimensions in all loops by the corresponding dynamic sizes (stored or extracted from the vectors). For example:
Matrix& operator +(Matrix& a, Matrix b)
{
unsigned int rows = a.Table.size();
unsigned int cols = a.Table[0].size();
for (unsigned int i = 0; i < rows; i++)
for (unsigned int j = 0; j < cols; j++)
a.Table[i][j] += b.Table[i][j];
return a;
}
However, this vector of vectors is not really effective. Better would be a single vector but I guess for a beginner it is okay.
Greetings
So, i'm making program that will multiply and adds matrices. I created class matrix with constructor:
class Matrix
{
private:
int row;
int column;
public:
int getRows()
{
return row;
}
int getColumns()
{
return column;
}
void print_matrix()
{
for(int i = 0; i < row; i++)
{
cout<<"\n";
for(int j = 0; j < column; j++)
cout<<matrix[i][j]<<"\t";
}
}
Matrix(int row, int column);
};
Matrix::Matrix(int row, int column)
{
this->row = row;
this->column = column;
int** matrix = new int*[row];
for(int i = 0; i < row; i++)
matrix[i] = new int[column];
for(int i = 0; i < row; i++)
for(int j = 0; j < column; j++)
matrix[i][j] = (i+j)*2*3/4;
for(int i = 0; i < row; i++)
delete[] matrix[i];
delete[] matrix;
}
at this point i dont know how to print my matrix, or work with him. In method "print_matrix" my compilator said that "'matrix was not declarated in this scope'".
You are deleting the allocated matrix in the constructor itself. To make it work,
add a member int**matrix in the class. And then do the allocation in constructor and delete it in destructor.
To add it further, even if you didn't delete the matrix then you would end up with the same error. The variable you have declared and used in the constructor - it's lifetime ends when the constructor ends.
Now instead of using pointer and allocating to it, why not use vector?
In that case you will keep std::vector v; as a member variable in the class and then resize it in constructor.
v.resize(row);
for (int i = 0; i < row; ++i)
v[i].resize(col);
I'm new to C++ and currently I'm trying to implement 2D matrix from classes, this is my current code, right now I'm unable to create an instance of the matrix object, please leave me feedback what I need to fix.
*Updated: I have fixed some of the code, but the matrix doesn't print anything
#include <iostream>
#include <cstdlib>
using namespace std;
class Matrix
{
public:
Matrix(); //Default constructor
Matrix(int *row, int *col); //Main constructor
void setVal(int row, int col, int val); //Method to set the val of [i,j]th-entry
void printMatrix(); //Method to display the matrix
~Matrix(); //Destructor
private:
int row, col;
double **matrix;
//allocate the array
void allocArray()
{
matrix = new double *[*row];
for (int count = 0; count < *row; count++)
*(matrix + count) = new double[*col];
}
};
//Default constructor
Matrix::Matrix() : Matrix(0,0) {}
//Main construcor
Matrix::Matrix(int *row, int *col)
{
allocArray();
for (int i=0; i < *row; i++)
{
for (int j=0; j < *col; j++)
{
*(*(matrix + i) + j) = 0;
}
}
}
//destructor
Matrix::~Matrix()
{
for( int i = 0 ; i < row ; i++ )
delete [] *(matrix + i) ;
delete [] matrix;
}
//SetVal function
void Matrix::setVal(int row, int col, int val)
{
matrix[row][col] = val;
}
//printMatrix function
void Matrix::printMatrix()
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
cout << *(*(matrix + i) + j) << "\t";
cout << endl;
}
}
int main()
{
int d1 = 2;
int d2 = 2;
//create 4x3 dynamic 2d array
Matrix object(&d1,&d2);
object.printMatrix();
return 0;
}
Your line
Matrix object = new int **Matrix(d1,d2);
is wrong. Use simply
Matrix object(d1,d2);
no need for Java-like syntax which in fact in C++ means dynamic allocation: Matrix* object = new Matrix(d1,d2);
Instead of Matrix object = new int **Matrix(d1,d2); use Matrix* object = new Matrix(d1,d2);
Also, you will have to use object->printMatrix(); instead of object.printMatrix();
I've absolutely no idea why my delete codes inside the destructor won't be able to functionally well. I hope u guys can help me for this.
Thank you so much!
class Array2D
{
public:
Array2D();
Array2D(int, int);
~Array2D();
private:
int row;
int col;
int **p;
};
Array2D::Array2D()
{
// Default Constructor
}
Array2D::Array2D(int rows, int cols)
{
this -> row = rows;
this -> col = cols;
p = new int* [row];
for(int i=0; i< row; i++)
p[i] = new int[col];
// Fill the 2D array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
p[i][j] = rand () % 100;
}
}
Array2D::~Array2D()
{
// I'm using this way to delete my 2D array.
// however, it won't work!
for (int i = 0; i < row; i++)
{
delete[]p[i];
}
delete[]p;
}
You are not initializing anything in your default constructor. That means that the destructor will go mad on a default constructed object. You are also not disabling the copy constructor, which is not functioning with your class, because if you have copied an object, it will try to delete the same table twice. Change it as follows, for example
class Array2D
{
public:
Array2D();
Array2D(int, int);
~Array2D();
private:
int row;
int col;
int **p;
void initialize(int rows, int cols);
// disable copy functions (make private so they cannot
// be used from outside).
Array2D(Array2D const&);
Array2D &operator=(Array2D const&);
};
Array2D::Array2D()
{
initialize(0, 0);
}
Array2D::Array2D(int rows, int cols)
{
initialize(rows, cols);
}
void Array2D::initialize(int rows, int cols) {
this -> row = rows;
this -> col = cols;
p = new int* [row];
for(int i=0; i< row; i++)
p[i] = new int[col];
// Fill the 2D array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
p[i][j] = rand () % 100;
}
}