overloading operator in D - d

I am trying to overload + but I got the errors:
#Error1 Error: no [] operator overload for type main.Matrix
Besides, I also got errors for measuring the time.
import std.stdio;
import std.c.process;
import std.date;
//#Error2
class Matrix
{
Matrix opBinary(string op)(Matrix another)
{
if(op == "+")
{
if (row != another.row || col != another.col)
{
// error
getchar();
return (this);
}
Matrix temp = new Matrix(row, col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
temp[i][j] = this[i][j] + another[i][j];
//#Error1
return temp;
}
}
};

m2[i][j] = this[i][j] + b[i][j];
You must define opIndex to use operations like this. E.g.:
double[] opIndex(size_t i1)
{
return d[i1];
}
double opIndex(size_t i1, size_t i2)
{
return d[i1][i2];
}
Or just inside of that method you might want to access double[][] directly:
m2.d[i][j] = this.d[i][j] + b.d[i][j];
std.date.d_time starttime = getCount();
Use StopWatch. E.g.:
StopWatch sw;
sw.start();
// operations...
sw.stop();
writefln("elapsed time = %s", sw.peek().msecs);

Related

Polynomial Class Project Problem with Division and Destructor C++

This is a project for my object oriented programming class. I need to introduce the followings: overloading + to sum two polynomials, overloading * to multiply a polynomial with a scalar or to multiply it with another polynomial, overloading [] to return coeficient on a specific position, method for adding , deleting a coeficient and evaluating polynom in a certain point (f(x)).
1.Everything is working besides the destructor. The destructor that should be used (delete [] coef) of Polynomial will break (Heap Coruption) if i use cout << A + B and i do not know why.
What i use right now is a workaround but it will not delete coef[0]. That's the point where it breaks. If you can help me somehow i will be gratefull. Can you understand what caused it?
2.I need to have one more overloaded operator, " / ". It should make division between two polynomials and I do not know how to implement it. I tried to search for it but i couldn't understand any algorithm. Any advice or algorithm explanation would be great, because i really do not know from where to start and i need to finish it until tommorrow morning.
3.If you have any advice on coding or efficienty will also be great ( project requirement: do not use STL ).
Thank you!
Polynomial.h:
#pragma once
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::istream;
class Polynomial
{
unsigned int deg;
double *coef;
public:
Polynomial() : deg(1), coef(new double[1]) {}
Polynomial(double [], int);
Polynomial(Polynomial&);
Polynomial& operator = (const Polynomial&);
~Polynomial();
friend ostream &operator <<(ostream&, const Polynomial&);
friend istream &operator >>(istream&, Polynomial&);
Polynomial operator + (const Polynomial) ;
double operator[] (unsigned int) const;
Polynomial operator * (int) const;
Polynomial operator * (const Polynomial obj) const;
unsigned int getDeg() { return this->deg; };
double eval(int);
void addCoef(double, int);
void delCoef(int);
};
inline Polynomial::Polynomial(double coefficients[], int number) : deg(number), coef(new double[number])
{
for (int i = 0; i < deg; i++) {
coef[i] = coefficients[i];
}
}
inline Polynomial::Polynomial(Polynomial &ob) {
this->deg = ob.deg;
this->coef = new double[deg];
for (int i = 0; i <= deg; i++)
{
this->coef[i] = ob.coef[i];
}
}
inline Polynomial::~Polynomial() {
for (int i = this->deg; i > 0; i--)
this->delCoef(i);
this->coef[0] = 0; //If i write it like this delete [] coef; it breaks.
this->deg = 0; //with HeapCoruption detected
}
Polynomial.cpp:
Polynomial& Polynomial::operator = (const Polynomial& obj)
{
if (this != &obj) //Testing to avoid situations like A = A;
{
this->deg = obj.deg;
for (int i = 0; i <= obj.deg; i++)
this->coef[i] = obj.coef[i];
}
return *this;
}
istream& operator >> (istream& in, Polynomial& obj)
{
in >> obj.deg;
cout << endl;
obj.coef = new double[obj.deg];
for (int i = 0; i <= obj.deg; i++)
{
in >> obj.coef[i];
}
return in;
}
ostream& operator << (ostream& out, const Polynomial& obj)
{
out << obj.deg << endl;
for (int i = 0; i <= obj.deg; i++)
{
if (obj.coef[i] != 0)
{
if (obj.coef[i] < 0)
out << '(' << obj.coef[i] << ')';
else
out << obj.coef[i];
if (i > 1)
out << "*x^" << i;
if (i == 1)
out << "*x";
if (i != obj.deg)
out << " + ";
}
}
out << endl <<endl;
return out;
}
Polynomial Polynomial::operator+ (const Polynomial obj)
{
Polynomial aux;
if (obj.deg >= deg)
{
aux.deg = obj.deg;
aux.coef = new double[obj.deg];
for (int i = 0; i <= deg; i++)
aux.coef[i] = obj.coef[i] + coef[i];
for (int i = deg + 1; i <= obj.deg; i++)
aux.coef[i] = obj.coef[i];
}
else // obj.deg < this->deg
{
aux.deg = deg;
aux.coef = new double[deg];
for (int i = 0; i <= obj.deg; i++)
{
aux.coef[i] = obj.coef[i] + coef[i];
}
for (int i = obj.deg + 1; i <= deg; i++)
{
aux.coef[i] = coef[i];
}
}
return aux;
}
double Polynomial::operator[] (unsigned int pos) const
{
if (pos > this->deg) {
throw std::out_of_range("Index bigger than polynomial length");
}
return this->coef[pos];
}
Polynomial Polynomial::operator * (const int scalar) const
{
Polynomial aux;
aux.deg = this->deg;
aux.coef = new double[aux.deg];
for (int i = 0; i <= aux.deg; i++)
aux.coef[i] = this->coef[i] * scalar;
return aux;
}
Polynomial Polynomial::operator * (const Polynomial obj) const
{
Polynomial aux;
aux.deg = obj.deg + this->deg;
aux.coef = new double[aux.getDeg()];
for (int i = 0; i <= aux.getDeg(); i++)
aux.addCoef(0, i);
for (int i = 0; i <= this->deg; i++)
for (int j = 0; j <= obj.deg; j++)
aux.coef[i+j] += (this->coef[i]) * obj.coef[j];
return aux;
}
double Polynomial::eval(int x) {
double sum = 0;
for (int i = 0; i <= this->deg; i++)
{
if (i == 0)
sum += this->coef[0];
else
{
int aux = i;
int xaux = x;
aux--;
while (aux != 0)
{
xaux *= x;
aux--;
}
sum += this->coef[i] * xaux;
}
}
return sum;
}
void Polynomial::addCoef(double NewCoef, int pos)
{
if (pos < 0)
return;
if (pos > this->deg)
{
double *newCoef = new double[pos];
for (int i = 0; i <= this->deg; i++)
newCoef[i] = this->coef[i];
for (int i = this->deg + 1; i < pos; i++)
newCoef[i] = 0;
newCoef[pos] = NewCoef;
this->coef = newCoef;
this->deg = pos;
return;
}
else
{
this->coef[pos] = NewCoef;
}
}
void Polynomial::delCoef(int pos)
{
if (pos > this->deg || pos < 0 )
return;
if (pos == this->deg)
{
this->coef[pos] = 0;
int degNoua = pos - 1;
while (this->coef[pos] == 0 && pos != 0)
pos--;
if (pos == 0 && this->coef[pos] == 0)
{
delete this->coef;
this->deg = 0;
}
else
{
this->deg = pos;
double *aux = new double[pos];
for (int i = 0; i <= pos; i++)
aux[i] = this->coef[i];
this->coef = aux;
}
}
else
{
this->coef[pos] = 0;
}
}

Operator*= from two instances (Matrix) gives bad results

I have a class Matrix, and I'm trying to implement the method operator*=, which i use to make the product of two instances(matrix): m1*=m2.
I tried both method with friend and two parameter, and without friend and 1 parameter, but in both cases the results it's bad. Only with one parameter and the this use gives me results similar to the right (not always).
Tried with friend and 2 parameter, and without friend and 1 parameter. Tried returning directly the first matrix, m1, also creating a temporary matrix m3
My private members:
int N, M;
T** data;
bool Init(const int N_, const int M_);
void Clear();
(i'm using init to initialize the matrix/bidimensional array):
bool Matrix::Init(const int N_, const int M_) {
this->Clear(); //dealloco comunque prima di inizializzarla
N = N_;
M = M_;
if (N <= 0 || M <= 0) {
cerr << "Non posso generare una matrixe: " << N <<"x"<< M << endl;
return false;
}
else if (N > 0 && M > 0) {
data = new T*[N];
for (int i = 0; i < N; i++) {
data[i] = new T[M];
}
}
return true;
}
My operator *= mathod (no friend, 1 parameter):
Matrix& Matrix::operator*=(const Matrix& m2) {
float operation = 0;
int N_ = (this->N < m2.N) ? this->N : m2.N;
int M_ = (this->M < m2.M) ? this->M : m2.M;
Matrix m3(N_, M_);
if (this->N != m2.M || this->M != m2.N) {
this->Set(0, 0, flag_stop);
}
else {
for (int i = 0; i < this->N; ++i) {
for (int j = 0; j < m2.M; ++j) {
for (int k = 0; k < this->M; ++k) {
operation = operation + (this->Get(i,k) * m2.Get(k,j)) ;
//cout << " Cout m1 su "<< i<< ","<<k<<":"<< this->Get(i,k) << "\t " << " Cout m2: "<< m2.Get(k,j) << endl;
this->Set(i, j, operation);
}
//cout << operation << "\t";
operation = 0;
}
operation = 0;
}
}
return *this;
}
In the main, when i try to use the operator*=:
Matrix m1(i1,j1);
Matrix m2(i2,j2);
//operator*=
cout << endl;
m1*=m2;
int N_ = (m1.GetN() < m2.GetN()) ? m1.GetN() : m2.GetN();
int M_ = (m1.GetM() < m2.GetM()) ? m1.GetM() : m2.GetM();
for (int i = 0; i < N_; ++i) {
for (int j = 0; j < M_; ++j) {
cout << m1.Get(i,j) << "\t";
}
cout << endl;
}
It's all the day that i try, but the results are not rights
i also tried with m1[2][2] and m2[2][2], with m1[3][2] and m2[2][3], etc... but nothing. Someone have had a similar problem?
Hoping to have right product of two matrixes, but i have, at the major times, big numbers (expected 5, obtained 30), or the first column right numbers, and the second not
The reason for mistakes you report seems to be the multiplication algorithm itself. Basically, your multiplication code is as follows:
for (int i = 0; i < this->N; ++i) {
for (int j = 0; j < m2.M; ++j) {
for (int k = 0; k < this->M; ++k) {
operation = operation + (this->Get(i,k) * m2.Get(k,j)) ;
this->Set(i, j, operation);
}
operation = 0;
}
}
Your algorithm modifies the original matrix just in the process of the calculation (this->Set() call) so when you call this->Get(i,k) for any i < j you obtain not an original value of the first matrix at ith row and kth column but a value that was already modified by this->Set() call. This apparently leads to wrong results.
In order to solve this you must ensure that you use original matrix values for your calculations, for example, by making a copy of the original matrix or (more optimal) of the currently modified row of the original matrix.

This is C++ program, about add two numbers

This is pacific question. The implementation of the class LargeInt will use a dynamic physical structure to store the individual digits of an integer, and will provide some basic I/O and arithmetic operations that can be performed on integers.
In particular, the class should include:
A default constructor
An operator function to overload the operator +
An operator function to overload the operator ==
An operator function to overload the operator <<
An operator function to overload the operator >>
Note 1: since the LargeInt class does not contain pointers, there is no need for a copy constructor or a destructor.
#include "targetver.h"
using namespace std;
class LargeInt
{
private:
char datain[200];
int databit[200];
int len;
int overflow;
LargeInt(char *x, int inlen)
{
int i = 0;
int j = inlen - 1;
len = inlen;
overflow = 0;
for (i = 0; i < 200; i++)
{
databit[i] = 0;
datain[i] = '\0';
}
for (i = 0; i < len; i++)
{
datain[i] = x[j];
j--;
}
}
~LargeInt();
void GetDataBit()
{
int i = 0;
for (i; i < len; i++)
databit[i] = datain[i] - 48;
}
public:
LargeInt& operator+(LargeInt& data);
bool operator==(LargeInt& data);
LargeInt& operator>>(int x);
LargeInt& operator<<(int x);
};
bool LargeInt::operator==(LargeInt& data)
{
if (this->len != data.len)
return false;
else
{
for (int i = 0; i < 200; i++)
{
if (this->databit[i] == data.databit[i])
continue;
else
return false;
}
return true;
}
}
LargeInt& LargeInt::operator+(LargeInt& data)
{
LargeInt t("0", 0);
int addlen;
if (this->len > data.len)
addlen = this->len;
else
addlen = data.len;
for (int i = 0; i < addlen; i--)
{
t.databit[i] = (data.databit[i] + this->databit[i] + t.overflow) % 10;
if ((data.databit[i] + this->databit[i] + t.overflow) >= 10)
t.overflow = 1;
}
t.len = addlen;
for (int i = 0; i < addlen; i++)
{
t.datain[i] = t.databit[i] + 48;
}
return t;
}
when I build it, it has a error like this
Warning 1 warning C4172: returning address of local variable or temporary.
LargeInt& LargeInt::operator+(LargeInt& data)
remove the & and your warning should go away. Right now the return is referencing a variable t, which is local to the function which has gone out of scope by the time the calling function catches the return.

Big integer calculator c++

So far I've got an add, subtract and print function as well as a constructor that initializes to zero the array. For some reason the operations(+ and -) made alot of sense to me(i think) so I kind of got ahead of my self and am not too sure how to initialize a big integer, could I get some help with a function such as
void assign(const bigint & A) or something like that? Also if there is something already wrong with my code please tell me. Thanks
const int size=30; //just to make things easier, will change to something big later
class bigint
{
int digits[size];
public:
// initializes to zero
bigint()
{
for (int i = 0; i < size; i++)
digits[i] = 0;
}
// prints a big int
void print()
{
bigint B;
for (int i = size - 1; i >= 0; i--)
{
int dig = B.digits[i];
if (dig != 0)
std::cout << dig;
}
}
// subtracts a bigint(B) from another(A)
void subtract(bigint & A, bigint & B)
{
for (int i = 0, borrow = 0; i < size; i++)
{
if (borrow = ((A.digits[i] -= B.digits[i] + borrow) < 0))
{
A.digits[i] += 10;
}
}
}
// adds a bigint(A) to another(B)
void add(bigint & A, bigint & B)
{
for (int i = 0, carry = 0; i < size; i++)
{
if (carry = ((A.digits[i] += B.digits[i] + carry) < 9))
{
A.digits[i] -= 10;
}
}
}
};

Vector values not saved permanently [C++ Rookie]

I overwrote a + operator:
Matrix& Matrix::operator+(Matrix m1)
{
//This should never be triggered
if(this->data.capacity() != m1.data.capacity() || this->data[0].capacity() != m1.data[0].capacity())
{
cout << "Dimensions don't match, can't add.\n";
throw 7;
}
vector<vector<double>> result;
result.resize(m1.data.capacity());
for(int i = 0; i < m1.data.size(); i++)
{
result[i].resize(m1.data[0].size());
for(int j = 0; j < m1.data[0].size(); j++)
{
result[i][j] = m1.data[i][j] + this->data[i][j];
}
}
return Matrix(m1.getRows(),m1.getCols(), result);
}
This is the corresponding Constructor:
Matrix::Matrix(int rows, int cols, vector<vector<double>> data)
{
this->rows = rows;
this->cols = cols;
this->data = data;
}
Here's the executing code:
c = (a+b);
When I assign a breakpoint at the last line of the operator overload, I can see the correct results in result and both cols and rows are assigned correctly. When I step out, c has "rows" and "cols" set correctly, but data is empty. Why is that?
Your operator + is wrong. It should be returning a new object, not a reference to a local object (which is UB anyway).