2D mesh class implementation in C++ - c++

I want to implement a 2D mesh class which is memory efficient, since it will be used in a Monte Carlo simulation. At this stage however, this is actually the same as a 2D array class. Needless to say, I am new to C++. I have written the following code.
#define MESH2D_H_INCLUDED
class Mesh2D
{
private:
double* mesh;
size_t rows;
size_t columns;
public:
/* constructor */
Mesh2D(size_t Nx, size_t Ny){
rows = Nx;
columns = Ny;
mesh = new double[Nx*Ny] {};
std::cout << "Mesh created." << std::endl;
}
/* destructor */
~Mesh2D()
{
delete[] mesh;
std::cout << "Mesh deleted." << std::endl;
}
/* accessors */
double getrows() const {return rows;}
double getcolumns() const {return columns;}
double& operator()(size_t i, size_t j)
{
if (i > rows || j > columns){
throw std::out_of_range("Index exceeds array bounds.");
}
return mesh[j + i*columns]; // row major access
}
/* copy constructor */
Mesh2D& operator=(const Mesh2D& rhs) // what is the difference between this line and the following? inline operator=(const Mesh2D& rhs)
{
if (rhs.rows != rows || rhs.columns != columns){
throw std::out_of_range("Assignment cannot be performed, mesh dimensions do not agree.");
}
mesh = new double [rows*columns];
// I want to avoid using a for loop
// for (int i=0; i<rows*columns; i++){
// mesh[i] = rhs.mesh[i];
// }
// Use this instead
memcpy(mesh, rhs.mesh, sizeof(rhs)); //however the output is not the expected.
std::cout << "copied!" << std::endl;
}
};
#endif // MESH2D_H_INCLUDED
//MAIN FUNCTION
#include <iostream>
#include "Mesh2D.h"
void PrintMesh2D(Mesh2D &mesh){ //why isn't it going to work if I add const? I mean: void PrintMesh2D(const Mesh2D &mesh)
for (int i=0; i<mesh.getrows(); i++){
for (int j=0; j<mesh.getcolumns(); j++){
std::cout << mesh(i,j) << " ";
}
std::cout << std::endl;
}
}
int main()
{
Mesh2D mesh{3,3};
Mesh2D newmesh{3,3};
for (int i=0; i<mesh.getrows(); i++){
for (int j=0; j<mesh.getcolumns(); j++){
mesh(i,j) = j + i * mesh.getcolumns();
}
}
newmesh = mesh;
PrintMesh2D(newmesh);
}
My questions are written as comments but I am listing them here as well:
Inside the copy constructor, what is the difference between this line Mesh2D& operator=(const Mesh2D& rhs) and this line inline operator=(const Mesh2D& rhs)?
Again, inside the copy constructor I would like to avoid a for loop and use memcpy instead. However, the output is not the expected, what am I doing wrong?
Inside the main function: Why is this not going to compile? void PrintMesh2D(const Mesh2D &mesh)
Finally, is the implementation complete? I mean, are there any important features/functions that are missing?
You are welcome to give me any piece of advice. Since I am new to C++, I have the feeling that I am writing bad buggy code.
EDIT:
I wrote the following as a copy constructor.
/* copy constructor */
Mesh2D (const Mesh2D& rhs)
{
rows = rhs.rows;
columns = rhs.columns;
mesh = new double[rows*columns];
memcpy(mesh,rhs.mesh,rows*columns*sizeof(double));
std::cout << "Copied!" << std::endl;
}
Looks right?

I will try and add the missing pieces to your code:
The copy constructor
A working assignment operator.
After the code below, I will comment:
#include <iostream>
#include <cstring>
#include <algorithm>
class Mesh2D
{
private:
size_t rows;
size_t columns;
double* mesh;
public:
Mesh2D(size_t Nx, size_t Ny) : rows(Nx), columns(Ny), mesh(new double[Nx*Ny]{})
{
std::cout << "Mesh created." << std::endl;
}
Mesh2D(const Mesh2D& rhs) : rows(rhs.rows), columns(rhs.columns),
mesh(new double[rhs.rows * rhs.columns])
{
memcpy(mesh, rhs.mesh, (rhs.rows * rhs.columns) * sizeof(double));
// or better yet
// std::copy(rhs.mesh, rhs.mesh + rhs.rows * rhs.columns, mesh);
}
Mesh2D& operator=(const Mesh2D& rhs)
{
if ( &rhs != this )
{
Mesh2D temp(rhs);
std::swap(temp.rows, rows);
std::swap(temp.columns, columns);
std::swap(temp.mesh, mesh);
}
return *this;
}
~Mesh2D()
{
delete[] mesh;
std::cout << "Mesh deleted." << std::endl;
}
double getrows() const {return rows;}
double getcolumns() const {return columns;}
double& operator()(size_t i, size_t j)
{
if (i > rows || j > columns){
throw std::out_of_range("Index exceeds array bounds.");
}
return mesh[j + i*columns]; // row major access
}
double& operator()(size_t i, size_t j) const
{
if (i > rows || j > columns){
throw std::out_of_range("Index exceeds array bounds.");
}
return mesh[j + i*columns]; // row major access
}
};
First, note the usage of the member-initialization list to initialize the members of the Mesh2D class. This is a good-habit to do things this way, instead of assigning inside the body of the constructor.
Second, note the assignment operator. It uses the copy / swap idiom to safely and cleanly deallocate the old memory and make a copy.
Third, the operator() should have a const overload, otherwise you could never use your class in something like this:
void foo(const Mesh2D& m)
{
std::cout << m(0,0);
}
The reason being that m is a const reference, thus you can only call const functions on it. Thus, the operator() needs a const version, along with the non-const version.
Also, the reason why the non-const version of operator() needs to also exist is that you may want to do this:
void foo2(Mesh2D& m)
{
m(0,0) = 23;
}
If m had only a const version of operator(), the above operation could not be done due to operator() changing the internal state of the object.
Another issue is that you are using memcpy incorrectly. The memcpy works on the number of bytes, not the number of items in an array. Thus you need to multiply by sizeof(double), since that's the byte count that you are copying. A more type-safe solution would be to use std::copy, which automatically uses the correct copying function using the number of items.
Last, the test for a bad "Mesh2D" has been removed from the assignment operator. The reason is that the assignment operator (and copy constructor) job is one thing and one thing only -- make copies.
When you start introducing business logic into the copy-assignment functions, you are risking making copies that are not copies, but instead pseudo-copies of the object being passed-in.
This leads to some of the nastiest and hardest-to-find bugs in C++, and that is when your copy-assignment functions want to play games and not really make copies. You know when you're doing something wrong if your copy constructor or assignment operator is making too many decisions and executing logic based on the passed-in value.
For completion, here is the same version of the class, but using std::vector<double>. Note how much smaller the code is, due to not needing a user-defined assignment operator, copy constructor, or destructor:
#include <iostream>
#include <vector>
class Mesh2D
{
private:
size_t rows;
size_t columns;
std::vector<double> mesh;
public:
Mesh2D(size_t Nx, size_t Ny) : rows(Nx), columns(Ny), mesh(Nx*Ny)
{
std::cout << "Mesh created." << std::endl;
}
double getrows() const {return rows;}
double getcolumns() const {return columns;}
double& operator()(size_t i, size_t j)
{
if (i > rows || j > columns){
throw std::out_of_range("Index exceeds array bounds.");
}
return mesh[j + i*columns];
}
const double& operator()(size_t i, size_t j) const
{
if (i > rows || j > columns) {
throw std::out_of_range("Index exceeds array bounds.");
}
return mesh[j + i*columns];
}
};

inline operator=(const Mesh2D& rhs) is a syntax error, it misses the return type. Also Mesh2D& operator=(const Mesh2D& rhs) is the copy assignment operator, not the copy constructor, that would be Mesh2D(const Mesh2D& rhs).
You can use memcpy, but the last argument should be the correct size rows*colums*sizeof(double). sizeof(rhs) is the size of the class object, which is unrelated to the array size. Since you are inside the copy assignment operator and not inside the copy constructor, the memory for mesh is already allocated, so you should remove mesh = new double [rows*columns]; from the copy assignment operator. You also have to do a return *this; there to match the return type.
Because then you need the const version of the functor: double operator()(size_t i, size_t j) const
read about rule of 3 or rule of 5, you should implement the copy constructor if you have a constructor and destructor.
from #PaulMcKenzie : Use std::vector to not have to do 1, 2, or 4.
Here is a full example: https://ideone.com/seOSwN

Related

operator overloading opertator + cant convert from pointer to const

i have a sparse matrix that is created with two arrays and each array index have a linked list the non zero numbers are in there including the i and j indexs
the header
class MNode {
public:
double _data;
int _indexI, _indexJ; // the place of the node in the matrix
// clarification: _nextRow is a pointer to the next columns in the row
MNode* _nextRow, *_nextCol;
MNode(double data, int i, int j);
};
private:
string _type;
MNode** _rowHead, **_colHead;
int _rowSize, _colSize;
int _elemNum;
void setValue(int, int, double);
void removeElement(int, int);
void insertNode(MNode*);
bool IsExist(int, int);
void setElementByType(int i, int j, double data);
public:
// construct a 'rows X cols' matrix.
SMatrix(int rows, int cols,string type);
// set the (i,j) element to be 'data'
void setElement(int i, int j, double data);
// destroy this matrix.
~SMatrix();
double getElement(int, int);
friend std::ostream& operator<<(std::ostream& os, const SMatrix& mat);
SMatrix& operator = (const SMatrix& other);
SMatrix & operator+(const SMatrix & other) const;
};
the cpp here is the overloading + function i get an erorr
cannot convert this pointer to const SMatrix to Smatrix&
SMatrix &SMatrix::operator +(const SMatrix& other) const {
SMatrix temp(3, 3, "any") ;
if (other._rowSize == this->_rowSize&&other._colSize == this->_colSize&&other._type == this->_type) {
for (int j = 0; j < other._colSize; j++) {
for (int i = 0; i < other._rowSize; i++) {
temp.setElement(i, j, (other.getElement(i, j) + this->getElement(i, j)));
}
}
}
return temp;
}
here is the contructor
SMatrix::SMatrix(int rows, int cols,string matType )
{
_type = matType;
_rowSize = rows;
_colSize = cols;
_elemNum = 0;
_rowHead = new MNode*[rows];
if (!_rowHead)
{
cout << "allocation error";
exit(1);
}
_colHead = new MNode*[cols];
if (!_colHead)
{
cout << "allocation error";
exit(1);
}
for (int i = 0; i < rows; i++)
{
_rowHead[i] = NULL;
}
for (int i = 0; i < cols; i++)
{
_colHead[i] = NULL;
}
}
iam not sure what i need to do the signature of the function is given and cant be chanbged any idea?
You've declared other to be a reference to const:
SMatrix & operator+(const SMatrix & other) const;
^^^^^
You call the member function getElement on that reference:
temp.setElement(i, j, (other.getElement(i, j) + this->getElement(i, j)));
^^^^^^^^^^^^^^^^
You've declared getElement to be non-const:
double getElement(int, int);
^
You may only call const member functions on const references.
the signature of the function is given and cant be chanbged any idea?
If the signature of getElement can't be changed, then you've been dealt a badly written signature. There should be no good reason why a getter couldn't be const. That said, since you're within the class, you can access all members directly without using a getter.
There's another bug. You've declared operator+ to return a reference.
SMatrix &SMatrix::operator +(const SMatrix& other) const
^
But you return a local automatic variable temp:
SMatrix temp(3, 3, "any") ;
// ...
return temp;
Automatic variables are destroyed at the end of the function. Therefore the returned reference will always be dangling and any use of it would have undefined behaviour.
the signature of the function is given and cant be chanbged any idea?
If the signature of operator+ can't be changed, then you've been dealt a badly written signature. The function really should return by value. There's no sensible solution that could return a reference. Using a static local would technically work, but that has some limitations on usage that aren't apparent from the interface.

Operator overloading "equal to"

I want to overload equal to "=" operator in C++ for
class Array
{
int *p;
int len;
};
All functions/constructor etc. are defined.
My question:
Could someone give me the prototype of the operator overloaded function?
And suppose:
Array a,b;
b=a;
Which of "a" and "b" would be passed implicitly and which explicitly?
Thanks in advance.
The prototype is Array& operator=(const Array& that).
While implementing this, remember about the rule of three and make good use of the copy-and-swap idiom.
You're looking for the assignment operator = (not equal-to, which is operator== and usually serves as an equality comparison)
class Array
{
int *p;
int len;
public:
// Assignment operator, remember that there's an implicit 'this' parameter
Array& operator=(const Array& array)
{
// Do whatever you want
std::cout << "assignment called";
return *this;
}
};
int main(void) {
Array a, b;
a = b;
}
remember that since you wrote "All functions/constructor etc. are defined" you should pay attention to what you need your class to do and possibly also implement destructor as in the rule of three (and/or take a look at its variants in C++11, might be relevant since there's no other code posted).
There is probably more than one way to do it, but here is an option.
Public Functions:
Array::Array(const Array& array)
{
Allocate(0);
*this = array;
}
Array::~Array()
{
Deallocate();
}
const Array& Array::operator=(const Array& array)
{
if (this == &array)
return *this;
Deallocate();
Allocate(array.len);
for (int i=0; i<len; i++)
p[i] = array.p[i];
return *this;
}
Non-Public Functions:
void Array::Allocate(int size)
{
len = size;
if (len > 0)
p = new int[len];
}
void Array::Deallocate()
{
if (len > 0)
delete[] p;
len = 0;
}
Of course, you can always use a vector<int> instead...

Error: "lvalue required as left operand of assignment"

I'm very much still a beginner at programming but I have come across the error "lvalue required as left operand of assignment" and I am unsure about how to resolve this issue after looking through various other discussions. The error appears in a class I made for Matrices when I overloaded certain operators. Here is part of the code,
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
#include "MVector.h"
class Matrix {
private:
vector<double> columns;
vector<vector<double> > A;
public:
//constructor
explicit Matrix(){};
explicit Matrix(int n,int m):columns(m),A(n,columns){};
explicit Matrix(int n,int m,double x):columns(m,x),A(n,columns){};
//destructor
~Matrix(){};
//equate matrices
Matrix &operator=(const Matrix &rhs) {A=rhs.A;return *this;};
//set all values to a double
Matrix &operator=(double x)
{
int rows=this->rows();
int cols=this->cols();
for (int i=0;i<rows;i++)
{
for (int j=0;j<cols;j++)
{
A[i][j]=x;
}
}
}
//access data in matrix (const)
double operator()(int i,int j) const {return A[i][j];};
//access data in matrix
double operator()(int i,int j) {return A[i][j];};
//returns the number of rows
int rows() const {return A.size();};
//returns the number of cols
int cols() const {return columns.size();};
//check if square matrix or not
bool check_if_square() const
{
if (rows()==cols()) return true;
else return false;
}
};
and this is one of the overloaded operators which produces the error
const Matrix operator+(const Matrix &A,const Matrix &B)
{
//addition of matrices
//check dimensions
if (!(A.cols()==B.cols()) || !(A.rows()==B.rows()))
{
cout << "Error: Dimensions are different \n Ref: Addition of Matrices";
throw;
}
else
{
int dim_rows = A.rows();
int dim_cols = B.cols();
Matrix temp_matrix(dim_rows,dim_cols);
for (int i=0;i<dim_rows;i++)
{
for (int j=0;j<dim_cols;j++)
{
temp_matrix(i,j)=A(i,j) + B(i,j);
}
}
return temp_matrix;
}
}
I assume I've done something wrong, if anyone can help and explain what I'm doing wrong that would be really appreciated. Thanks for the help!
It means that you cannot assign to the result of an rvalue-expression, in this case the temporary returned by operator()(int,int). You probably want to change your non-const operator()(int,int) in the Matrix class to be:
double& operator()( int x, int y ) { return A[i][j]; }
Additionally (and unrelated to the question) you might want to simplify your matrix class and store only the dimensions and a single one dimensional vector to store all the elements. Then the accessors would perform some basic arithmetic (something like row*columns()+column) to get to the actual value in the one dimensional vector.

Returning deep copies of objects when overloading the = operator

So I making a container class for integers and I want to overload the = operator so that I can return a deep copy of the object. My code works but the two objects point to the same address. This is the main.cpp file:
int main (int argc, const char * argv[]) {
IntList cArray(5);
for (int i = 0; i < cArray.getLength(); i++) {
cArray[i] = (i + 1) * 10;
}
using namespace std;
for (int i = 0; i < cArray.getLength(); i++)
cout << cArray[i] << " ";
cout << endl << popped << endl;
IntList cArray2(4);
for (int i = 0; i < cArray2.getLength(); i++)
cArray2[i] = i * 5;
cArray2 = cArray;
cArray2[2] = 1000;
for (int i = 0; i < cArray.getLength(); i++)
cout << cArray[i] << " ";
cout << endl;
for (int i = 0; i < cArray2.getLength(); i++)
cout << cArray2[i] << " ";
cout << endl;
return 0;
}
This is the header file for the IntList class:
class IntList {
private:
int _length;
int* _data;
public:
IntList(int length);
~IntList();
void erase();
void reallocate(int length); // Faster way to call erase() and resize()
void resize(int length);
void insert(int value, int index);
void prepend(int value);
void append(int value);
int pop(int index);
void removeBefore(int index); // Exclusive
void removeAfter(int index); // Exclusive
int getLength();
int indexOf(int value);
int& operator[](int index);
IntList operator=(IntList* source);
};
And this is the implementation of IntClass's operator=() method:
IntList IntList::operator=(IntList* source) {
_length = source->getLength();
reallocate(_length);
for (int i = 0; i < _length; i++) {
_data[i] = (*source)[i];
}
return *this;
}
You're not working with pointers to IntList - operator= typically takes a const & and returns a reference to the instance being assigned to.
IntList & IntList::operator=(IntList const & source) {
...
return *this;
}
Remember that you also need a copy constructor: IntList(IntList const & source)
You can make an operator= which takes a pointer to IntList - that would only work if you did something like this:
IntList l1;
IntList l2;
l1 = &l2;
This isn't typical usage, and you should rather be explicit if you require this, use e.g. void IntList::copyFrom(IntList const *) in this case.
Other changes you should make:
Add this:
int operator[](int index) const;
Make these const:
int getLength() const;
int indexOf(int value) const;
Because your assignment operator takes a pointer to an IntList, you would need to call it like this:
cArray2 = &cArray;
Your example code is using the default assignment operator generated by your compiler. Your assignment operator should have this declaration instead:
IntList& IntList::operator=(IntList const& source)
IntList IntList::operator=(IntList* source)
Wrong signature for operator=, as it's parameter type is a pointer to IntList
Correct signature is this:
IntList & IntList::operator=(const IntList & source) //reference of source!
//^^^ note this ^^^ note this as well!
That is, make both parameter type as well as return type reference.
Your operator needs the signature IntList& operator=(const IntList& source);. Note the reference instead of the pointer, and that you must RETURN by reference as well to allow assignment chaining. When you pass it by pointer anywhere implicit assignment is required the compiler-generated shallow copy assignment operator will be used.
EDIT: You also need to make getLength const so that it's able to be called inside the assignment operator.

How to pass two-dimensional array as an argument?

My Matrx class is defined as
class Matrx
{
double A[50][50];
int m,n;
public:
Matrx(void);
Matrx(int a, int b)
{
m=a;
n=b;
}
Matrx operator +(Matrx b);
Matrx Transpose(Matrx b);
Matrx operator *(Matrx b);
CString printMatrx();
void readMatrx(double a[][]);
Matrx TransposeMat(Matrx b);
};
void Matrx::readMatrx(double a[][])
{
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
A[i][j]=a[i][j];
}
}
The intellisense gives error like the below
1 IntelliSense: an array may not have elements of this type d:\bmadaptive_dd_v1.02\matrx.h 17 27 TestServer
Why?
How to pass a two dimensional array as argument of the function?
The problem is that when passing multidimensional arrays as parameters in C++, you must specify the dimension of the outermost array. For example:
void ThisIsIllegal(int arr[][]); // Wrong!
void ThisIsAlsoIllegal(int arr[10][]); // Also wrong
void ThisIsLegal(int arr[][10]); // Okay
If you want to be able to have a function that takes in an array of any size, you can use templates:
template <size_t N, size_t M>
void ThisIsAlsoLegal(int (&arr)[M][N]);
This last version accepts any multidimensional array of the right type, and is probably what you're looking for.
You need to properly learn about arrays and pointers. This includes the lesson "huh! They are not as useful as I thought they were". After you've gotten familiar with how arrays and pointers work exactly you should rethink your design.
For example, in my opinion, the following design has lots of advantages:
#ifndef MATRIX_HPP_INCLUDED
#define MATRIX_HPP_INCLUDED
#include <vector>
#include <algorithm>
class matrix
{
public:
typedef std::vector<double>::size_type st;
matrix() : rows_(0), cols_(0) {}
matrix(int r, int c) : rows_(r), cols_(c), coeffs_(st(r)*c,0.0) {}
void reset(int r, int c)
{ rows_=r; cols_=c; coeffs_.clear(); coeffs_.resize(st(r)*c,0.0); }
int rows() const {return rows_;}
int cols() const {return cols_;}
double const& operator()(int i, int j) const {return coeffs_[indexof(i,j)];}
double & operator()(int i, int j) {return coeffs_[indexof(i,j)];}
double const* operator[](int i) const {return &coeffs_[indexof(i,0)];}
double * operator[](int i) {return &coeffs_[indexof(i,0)];}
void swap(matrix& that)
{
std::swap(this->rows_,that.rows_);
std::swap(this->cols_,that.cols_);
this->coeffs_.swap(that.coeffs_));
}
private:
int rows_, cols_;
std::vector<double> coeffs_;
st indexof(int i, int j) const {return st(i)*cols+j;} // row major storage
};
inline void swap(matrix& a, matrix& b) {a.swap(b);}
matrix& operator+=(matrix& lhs, matrix const& rhs);
matrix operator+(matrix const& lhs, matrix const& rhs);
matrix operator*(matrix const& lhs, matrix const& rhs);
inline matrix& operator*=(matrix& lhs, matrix const& rhs)
{ matrix tmp = lhs * rhs; swap(tmp,lhs); return lhs; }
...
#endif
This way you won't waste any space for small matrices, and you can support large matrices. Also, the use of std::vector instead of a pointer member which points to dynamically allocated memory removes the need to define your own copy constructor, assignment operator and destructor.
Of course, you could use boost::multi_array as a matrix replacement but using a custom matrix class allows you to declare overloaded operators in your own namespace which is desirable due to ADL (argument dependent lookup).
You might think that this doesn't really answer your question. In that case, let me stress that I think you don't fully understand how arrays and pointers work / behave. This is something you should look up in a decent C++ book. One could write many pages about this topic. You can't expect to see a short answer explaining all the quirks.
Check out the Definite C++ Book Guide thread.
You need to specify all but the first dimension, e.g.
void Matrx::readMatrx(double a[][50])
From this you should be able to see that you have a fundamental problem with the way you have implemented your class, but at least you should now be able to get the code to compile.
You can to specify all dimensions or only last dimension to pass an array:
void Matrx::readMatrx(double a[][50])
{
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
A[i][j]=a[i][j];
}
}
Thanks to all of you people...you were really helping...I have found myself a new definition of the class and the function definition for the matrix that fitted my need. I need you r comment on it...Below is the example of the class declaration..
#include<iostream>
#include"stdafx.h"
using namespace std;
const int M=100; const int N=100;
class Matrix
{
double A[M][N];
int m,n;
public:
Matrix(void);
Matrix(int a, int b)
{
m=a;
n=b;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
A[i][j]=0.0;
}
}
Matrix operator +(Matrix b);
Matrix operator -(Matrix b);
Matrix operator *(Matrix b);
void TransPose(Matrix b);
CString printMatrix();
void readMatrix(double*);
};
and then the function implementation
#include "stdafx.h"
#include "Matrix.h"
Matrix::Matrix(void)
{
}
Matrix Matrix::operator *(Matrix b)
{
Matrix c(m,m);
if(n!=b.m)
{
HWND hndOwner(0);
MessageBoxW(hndOwner,L"Multiplication not possible row and column does not match",L"Error",NULL);
Matrix errMat(1,0);
double er[1][1]={0}; errMat.readMatrix((double *)er);
return errMat;
}
for(int i=0;i< m;i++)
{
for(int k=0;k< m;k++)
{
c.A[i][k]=0;
for(int j=0;j< n;j++)
{
c.A[i][k] = c.A[i][k]+(A[i][j] * b.A[j][k]) ;
}
}
}
return c;
}
Matrix Matrix::operator +(Matrix b)
{
Matrix c(m,n);
if((n!=b.n)||(m!=b.m))
{
HWND hndOwner(0);
MessageBoxW(hndOwner,L"Addition not possible row and column does not match",L"Error",NULL);
Matrix errMat(1,0);
double er[1][1]={0}; errMat.readMatrix((double *)er);
return errMat;
}
for(int i=0;i<m;i++)
{
for(int j=0;j< n;j++)
{
c.A[i][j]=0.0;
}
}
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
{
c.A[i][j]=A[i][j]+b.A[i][j];
}
}
return c;
}
CString Matrix::printMatrix()
{
CString strB(" "),strDisp;
for(int iRow=0;iRow<m;iRow++)
{
for(int iColumn=0;iColumn<n;iColumn++)
{
strB.Format(L"%lf ",A[iRow][iColumn]);
strDisp+=strB;
}
strDisp+="\r\n";
}
return strDisp;
}
void Matrix::readMatrix(double *ptrarr)
{
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
A[i][j]=*(ptrarr+i*n+j);
}
}
void Matrix::TransPose(Matrix b)
{
for(int i=0;i<b.n;i++)
{
for(int j=0;j<b.m;j++)
A[i][j]=b.A[j][i];
}
}
The simple codes in the above are working well till now...if you have any suggestion for the improvement please suggest..
You're lucky, then because:
for(int j=0;j<m;j++)
A[i][j]=0.0;
should probably be:
for(int j=0;j<**n**;j++)
A[i][j]=0.0;