My own vector class - c++

I am trying to create my own vector class. I want to overload the basic features of STL vector. My code is compiling by after testing it, a message "segmentation fault(core dumped is)" is shown. Could you show me where I can improve my code. Thank you in advance!
#include<iostream>
#include<fstream>
using namespace std;
class Vector
{
public:
Vector();
Vector(const Vector& vect);
~Vector();
Vector& operator =(const Vector& vect);
void insert(double element);
bool operator ==(const Vector& vect);
Vector& operator +(const Vector& vect);
Vector& operator -(const Vector& vect);
Vector& operator *(const Vector& vect);
int size();
double operator[](int num);
friend istream& operator >>(istream& input, Vector& vect);
friend ostream& operator <<(ostream& output, Vector& vect);
private:
double* data;
int num;
int max;
};
Vector:: Vector()
{
double* data = NULL;
int num = 0;
int max = 0;
}
Vector::Vector(const Vector& vect)// not sure if its correct
{
data = new double[vect.max];
memcpy(data, vect.data, sizeof(double) * vect.num);
num = vect.num;
max = vect.max;
}
Vector::~Vector()
{
if(data)
{
delete[] data;
data = 0;
}
}
void Vector:: insert(double element)
{
if(num < max)
{
*(data + num) = element;
}
else
{
double *tmp = new double[num * 2];
delete[] data;
*(data + num) = element;
max *= 2;
}
num++;
}
Vector& Vector:: operator = (const Vector& vect)// highly unlikely to be correct
{
if(this != &vect)
{
if(data)
{
delete[] data;
data = 0;
}
max = vect.max;
data = new double[max];
for(int i = 0; i < num; i++)
{
this->data[i] = vect.data[i];
}
}
return *this;
}
bool Vector:: operator ==(const Vector& vect)
{
bool isEqual = true;
if(this->num != vect.num)
{
isEqual = false;
}
for(int i = 0; i < num; i++)
{
if(this->data[i] != vect.data[i] )
{
isEqual = false;
}
}
return isEqual;
}
Vector& Vector:: operator +(const Vector& vect)
{
Vector result;
for (int i = 0; i < num; ++i)
{
result.insert(*(data + i) + *(vect.data + i));
}
return result;
}
Vector& Vector:: operator -(const Vector& vect)
{
Vector result;
for (int i = 0; i < num; ++i)
{
result.insert(*(data + i) - *(vect.data + i));
}
return result;
}
Vector& Vector::operator*(const Vector &vect)
{
Vector result;
for (int i = 0; i < num; ++i)
{
result.insert(*(data + i) * *(vect.data + i));
}
return result;
}
int Vector:: size()
{
return num;
}
double Vector::operator[](int num)
{
return *(data + num);
}
ostream &operator <<(ostream &output, Vector &vect)
{
output << "[";
for (int i = 0; i < vect.size(); ++i)
{
output << vect[i];
if (i < vect.size() - 1)
output << ",";
}
output << "]\n";
return output;
}
istream &operator >>(istream &input, Vector &vect)
{
double element;
input >> element;
vect.insert(element);
return input;
}
int main()
{
Vector vec;
for (int i = 0; i < 10; ++i)
{
vec.insert(i);
}
return 0;
}

Look closely at your insert function. Specifically at how you are re-sizing the array.

Related

Operator Overloading: Failed to return an object through *this

The class "vector" is declared as below:
class Vector
{
private:
float *arr;
int currentIndex;
int arrSize;
public:
Vector();
Vector(int size);
Vector(const Vector& V);
~Vector();
float length();
Vector normalize();
Vector operator +(const Vector &v);
Vector operator =(const Vector &v);
Vector operator -(const Vector &v);
};
I defined "operator +" and "operator =" as below:
Vector Vector::operator +(const Vector &v)
{
for (int i = 0; i < arrSize; i++)
{
arr[i] += v.arr[i];
}
return *this;
}
Vector Vector::operator=(const Vector &v)
{
if (this != &v)//to avoid case "v = v"
{
arrSize = v.arrSize;
currentIndex = v.currentIndex;
delete [] arr;
arr = new float [arrSize];
for (int i = 0; i < arrSize; i++)
{
arr[i] = v.arr[i];
}
}
return *this;
}
main:
//...declared v1, v2 and v3...
v3 = v1 + v2;
cout << v3 << endl;
v3 receive unexpected values.
Please tell me which part did I implemented wrongly and how could I fix it.
Thanks.
You are trying to implement operator+() so you don't want to edit anything in memory for that object (That would be the job of operator+=()).
You'd do this:
Vector Vector::operator+(const& Vector v) //Note it's Vector, not Vector&
{
//You probably want to verify that the vectors are the same size?
assert(arrSize == v.arrSize); //You can do this some other way as well
Vector out = Vector(arrSize); //Create a new object on the heap to return
for (int i = 0; i < arrSize; i++)
out.arr[i] = arr[i] + v.arr[i]; //Do the addition
return out;
}
And then your operator=() class would look like:
Vector& Vector::operator=(const& Vector v) //Note the return type of Vector&
{
if (this != &v) //This check is probably superflous
{
arrSize = v.arrSize;
currentIndex = v.currentIndex;
delete[] arr;
arr = new float[arrSize];
for (int i = 0; i < arrSize; i++)
arr[i] = v.arr[i];
}
return *this;
}

Expected { at the end of output

I am trying to run my code from past few days but these errors are just not going away. The code is running smoothly in Code blocks but generating errors in Linux.
The errors are:
Matrix.h:14:20: error: expected ‘)’ before ‘rows’
Matrix(std::size_t rows, std::size_t cols, double initValue)
^~~~
Matrix.h:234:2: error: expected ‘}’ at end of input
};
^
Matrix.h:10:20: error: expected unqualified-id at end of input
double *p = nullptr;
I have already checked the semi colons and brackets and they seem to be all right.
My code is
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
private:
int r, c, z;
double *p = nullptr;
public:
Matrix(std::size_t rows, std::size_t cols, double initValue)
{
r = rows;
c = cols;
z = r*c;
p = new double [z];
for(int i=0; i<z; ++i)
{
p[i]=initValue;
//cout<< p[i];
}
}
~Matrix()
{
delete [] p;
}
Matrix(const Matrix& m1) : r(m1.r), c(m1.c), z(r*c)
{
p = new double [z];
for (int i=0; i<z; ++i)
{
p[i]=m1.p[i];
}
}
//= operator overloading
Matrix& operator=(const Matrix& m1)
{
if (*this == m1)
return *this;
else
{
r= m1.r;
c=m1.c;
z=r*c;
delete[] p;
p=nullptr;
p= new double[m1.z];
for(int i=0;i<z;++i)
{
p[i]=m1.p[i];
}
return *this;
}
}
double& operator()(std::size_t i, std::size_t j)
{
return p[i*c+j];
}
const double& operator()(std::size_t i, std::size_t j) const
{
return p[i*c+j];
}
bool operator ==(const Matrix& m1) const
{
if(r==m1.r && c==m1.c)
{
for(int i=0;i<z;++i)
{
if (p[i]!=m1.p[i])
{
return false;
}
}
}
else if(r!=m1.r || c!=m1.c)
{
return false;
}
return true;
}
bool operator !=(const Matrix& m1) const
{
if( r!=m1.r || c!=m1.c)
{
return true;
}
for(int i=0;i<m1.z;++i)
{
if (p[i]!= m1.p[i])
{
return true;
}
}
return false;
}
Matrix& operator +=(const Matrix& m1)
{
for(int i=0;i<z;++i)
{
p[i]=p[i]+m1.p[i];
}return *this;
}
Matrix operator +(const Matrix& m1) const
{
Matrix m3 (r,c,0);
for(int i=0;i<z;++i)
{
m3.p[i]=p[i]+m1.p[i];
}
return m3;
}
Matrix& operator -=(const Matrix& m1)
{
for(int i=0;i<z;++i)
{
p[i]=p[i]-m1.p[i];
}return *this;
}
Matrix operator -(const Matrix& m1) const
{
Matrix m3 (r,c,0);
for(int i=0;i<z;++i)
{
m3.p[i]=p[i]-m1.p[i];
}
return m3;
}
Matrix operator *(const Matrix& m1) const
{
Matrix m3 (r,m1.c,0);
double s=0; //temp
if(c==m1.r)
{
for(int i=0;i<r;++i)
{
for(int j=0;j<m1.c;++j)
{
for(int k=0;k<m1.r;++k)
{
s+=this-> operator()(i,k)*m1(k,j);
}
m3.p[i*(m1.c)+j]=s;
s=0;
}
}return m3;
}
else
{
std::cout<<"Matrices are not compatible";
}
}
Matrix& operator *=(const Matrix& m1)
{
/*Matrix m3 (r,m1.c,0);
double s=0; //temp
for(int i=0;i<r;++i)
{
for(int j=0;j<m1.c;++j)
{
for(int k=0;k<m1.r;++k)
{
s+=this-> operator()(i,k)*m1(k,j);
}
m3.p[i*(m1.c)+j]=s;
s=0;
}
}
*this=m3;*/
*this = *this *m1;
return *this;
}
std::size_t rows() const
{
return r;
}
std::size_t cols() const
{
return c;
}
friend std::ostream& operator <<(std::ostream& x, const Matrix& m1)
{
for( int i=0;i<m1.r;++i)
{
for(int j=0;j<m1.c;++j)
{
x<<m1.p[i*m1.c+j]<<"\t";
}
std::cout<<std::endl;
}return x;
}
friend std::istream& operator >>(std::istream& y, Matrix& m1)
{
{
for( int i=0;i<m1.r;++i)
{
for(int j=0;j<m1.c;++j)
{
y>>m1.p[i*m1.c+j];
}
}
return y;
}
}
};
#endif // MATRIX_H
Please do let me know as to where I am wrong or missing something! I am trying to run MatrixProduct.cpp for different test cases.
Thanks in Advance.
So, as much as it is fast and convenient to put code into a header, it almost always leads to compile errors that take longer to track down than the time it takes to create the standard .h and .cpp files, especially with this much code.
I'm not exactly sure where the problem was, but it may have been the Matrix::operator>>(). You'll be able to find errors like this by using an IDE like eclipse and pressing Ctrl-i to auto-indent the code. Also, please check that I didn't mess up any of your logic formatting it.
Also, there's some academic trick question about memory allocation for matrices. if I remember correctly, you are supposed to allocate all the memory at once and then use pointers to refer to the array elements. I could be wrong and I'm not going to go into it now. Something like:
int rows(10000);
int cols(10000);
double* _data = (double*) malloc(rows * cols * sizeof(double));
double** data = (double**) malloc(rows * sizeof(double*));
for(int i = 0; i < rows; i++) {
data[i] = _data + (cols * i);
}
Please note that I have no idea if the matrix math is correct
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <istream>
#include <ostream>
class Matrix {
public:
Matrix(std::size_t rows, std::size_t cols, double initValue);
Matrix(const Matrix& m1);
~Matrix();
Matrix& operator=(const Matrix& m1);
double& operator()(std::size_t i, std::size_t j);
const double& operator()(std::size_t i, std::size_t j) const;
bool operator==(const Matrix& m1) const;
bool operator!=(const Matrix& m1) const;
Matrix& operator+=(const Matrix& m1);
Matrix operator+(const Matrix& m1) const;
Matrix& operator-=(const Matrix& m1);
Matrix operator-(const Matrix& m1) const;
Matrix operator*(const Matrix& m1) const;
Matrix& operator*=(const Matrix& m1);
std::size_t rows() const;
std::size_t cols() const;
friend std::ostream& operator<<(std::ostream& x, const Matrix& m1);
friend std::istream& operator>>(std::istream& y, Matrix& m1);
private:
int r, c, z;
double *p;
};
#endif
matrix.cpp
#include "matrix.h"
#include <iostream>
#include <istream>
#include <ostream>
Matrix::Matrix(std::size_t rows, std::size_t cols, double initValue) :
r(rows),
c(cols),
z(r * c) {
p = new double [z];
for(int i = 0; i < z; ++i) {
p[i] = initValue;
}
}
Matrix::Matrix(const Matrix& m1) :
r(m1.r),
c(m1.c),
z(r*c) {
p = new double [z];
for (int i=0; i<z; ++i) {
p[i]=m1.p[i];
}
}
Matrix::~Matrix() {
delete [] p;
}
Matrix& Matrix::operator=(const Matrix& m1) {
if (*this == m1) {
return *this;
} else {
r = m1.r;
c = m1.c;
z = r * c;
delete[] p;
p = nullptr;
p = new double[m1.z];
for(int i = 0; i < z; ++i) {
p[i] = m1.p[i];
}
return *this;
}
}
double& Matrix::operator()(std::size_t i, std::size_t j) {
return p[i*c+j];
}
const double& Matrix::operator()(std::size_t i, std::size_t j) const {
return p[i*c+j];
}
bool Matrix::operator==(const Matrix& m1) const {
if(r==m1.r && c==m1.c) {
for(int i=0;i<z;++i) {
if (p[i] != m1.p[i]) {
return false;
}
}
} else if(r != m1.r || c != m1.c) {
return false;
}
return true;
}
bool Matrix::operator!=(const Matrix& m1) const {
if( r != m1.r || c != m1.c) {
return true;
}
for(int i = 0; i < m1.z; ++i) {
if (p[i] != m1.p[i]) {
return true;
}
}
return false;
}
Matrix& Matrix::operator+=(const Matrix& m1) {
for(int i=0;i<z;++i) {
p[i] = p[i] + m1.p[i];
}
return *this;
}
Matrix Matrix::operator+(const Matrix& m1) const {
Matrix m3 (r,c,0);
for(int i=0;i<z;++i) {
m3.p[i] = p[i] + m1.p[i];
}
return m3;
}
Matrix& Matrix::operator-=(const Matrix& m1) {
for(int i=0;i<z;++i) {
p[i] = p[i] - m1.p[i];
}
return *this;
}
Matrix Matrix::operator-(const Matrix& m1) const {
Matrix m3 (r, c, 0);
for(int i=0;i<z;++i) {
m3.p[i] = p[i] - m1.p[i];
}
return m3;
}
Matrix Matrix::operator*(const Matrix& m1) const {
Matrix m3 (r, m1.c,0 );
double s = 0;
if(c == m1.r) {
for(int i = 0; i < r; ++i) {
for(int j = 0; j < m1.c; ++j) {
for(int k = 0; k < m1.r; ++k) {
s += this->operator()(i,k)*m1(k,j);
}
m3.p[i * (m1.c) + j] = s;
s = 0;
}
}
return m3;
} else {
std::cout << "Matrices are not compatible";
}
}
Matrix& Matrix::operator*=(const Matrix& m1) {
*this = *this *m1;
return *this;
}
std::size_t Matrix::rows() const {
return r;
}
std::size_t Matrix::cols() const {
return c;
}
std::ostream& operator<<(std::ostream& x, const Matrix& m1) {
for( int i=0;i<m1.r;++i) {
for(int j=0;j<m1.c;++j) {
x << m1.p[i*m1.c+j] << "\t";
}
std::cout << std::endl;
}
return x;
}
std::istream& operator>>(std::istream& y, Matrix& m1) {
for( int i=0;i<m1.r;++i) {
for(int j=0;j<m1.c;++j) {
y >> m1.p[i * m1.c + j];
}
}
return y;
}

Polynomial multiplication recursively

Here is my code, why is it showing segmentation fault? Can someone correct my mult4 function... I know that problem is mult4 and i am not sure is function mult4 is correct solution for polynomial recursively multiplication...
#include <iostream>
#include <cstdlib>
using namespace std;
class Polynomial
{
public:
Polynomial()
{
deg=0;
coeff = new float[deg+1];
coeff[0]=0;
}
Polynomial(int n)
{
deg = n;
coeff = new float[deg+1];
for(int i = 0; i<=deg;i++)
coeff[i] = rand()/(float)RAND_MAX;
}
Polynomial(float *array, int n)
{
deg=n;
coeff=array;
}
Polynomial(const Polynomial& P)
{
deg = P.deg;
coeff = new float[deg+1];
for(int i=0;i<=deg;i++) coeff[i] = P.coeff[i];
}
~Polynomial()
{
delete []coeff;
}
Polynomial operator+(const Polynomial& P) const;
Polynomial operator-(const Polynomial& P) const
{
int i;
Polynomial c;
if(deg>=P.deg)
{
c.deg=deg;
for(i=deg;i>=0;i--)
c.coeff[i]=coeff[i];
for(i=P.deg;i>=0;i--)
c.coeff[i]=c.coeff[i]-P.coeff[i];
}
else
{
c.deg=P.deg;
for(i=P.deg;i>=0;i--)
c.coeff[i]=-P.coeff[i];
for(i=deg;i>=0;i--)
c.coeff[i]=c.coeff[i]+coeff[i];
}
return c;
}
Polynomial& operator=(const Polynomial& P)
{
if (this!=&P)
{
delete [] coeff;
deg = P.deg;
coeff = new float[deg+1];
for(int i=deg;i>=0;i--) coeff[i] = P.coeff[i];
}
return (*this);
}
float operator[](float x) // evaluation of polynomial
{
float rez=0;
for(int i=deg;i>=0;i--)
rez=rez*x+coeff[i];
return rez;
}
int degree() const
{
return deg;
}
public:
float *coeff; // array- representation of polynomial
int deg; //degree of polynomial
friend ostream& operator<<(ostream &out, const Polynomial& P) //overload operatpr<<
{
for ( int i =P.deg; i >= 0; i-- )
{
out << P.coeff[i] << "x^" << i << " ";
if(i>=1)
{
if(P.coeff[i-1]>0) out<<"+";
}
}
out << endl;
return out;
}
};
Polynomial Polynomial::operator+(const Polynomial& P) const
{
int i;
Polynomial c;
if(deg>=P.deg)
{
c.deg=deg;
for(i=deg;i>=0;i--)
c.coeff[i]=coeff[i];
for(i=P.deg;i>=0;i--)
c.coeff[i]=c.coeff[i]+P.coeff[i];
}
else
{
c.deg=P.deg;
for(i=P.deg;i>=0;i--)
c.coeff[i]=P.coeff[i];
for(i=deg;i>=0;i--)
c.coeff[i]=c.coeff[i]+coeff[i];
}
return c;
}
Polynomial shift(Polynomial A, int x)
{
Polynomial c(A.deg+x);
int k=0;
for(int i=c.deg;i>=0;i--)
c.coeff[i]=0;
for(int i=A.deg;i>=0;i--)
{
c.coeff[c.deg-k]=A.coeff[i];
k++;
}
return c;
}
Polynomial mult4( Polynomial P, Polynomial Q)
{
if(P.deg==1)
{
Polynomial qw(2);
qw.coeff[0]=P.coeff[0]*Q.coeff[0];
qw.coeff[2]=P.coeff[1]*Q.coeff[1];
qw.coeff[1]=P.coeff[1]*Q.coeff[0]+Q.coeff[1]*P.coeff[0];
return qw;
}
else
{
Polynomial p1(((P.deg)/2)-1);
Polynomial p2(P.deg-(P.deg)/2);
Polynomial q1(((Q.deg)/2)-1);
Polynomial q2(Q.deg-(Q.deg)/2);
int k=0;
for(int i=p1.deg;i>=0;i--)
{
p1.coeff[i]=P.coeff[i];
}
for(int i=p2.deg;i>=0;i--)
{
p2.coeff[i]=P.coeff[P.deg-k];
k++;
}
for(int i=q1.deg;i>=0;i--)
{
q1.coeff[i]=Q.coeff[i];
}
k=0;
for(int i=q2.deg;i>=0;i--)
{
q2.coeff[i]=Q.coeff[P.deg-k];
k++;
}
Polynomial t1,t2,t3;
t1=mult4(p1+p2,q1+q2);
t2=mult4(p1,q1);
t3=mult4(p2,q2);
return(t2+shift(t1-t2-t3,P.deg/2)+shift(t3,2*(P.deg/2)));
}
}
int main()
{
float *p=new float[4];
for(int i=3;i>=0;i--)
p[i]=-1.1+i;
float *k=new float[5];
for(int i=4;i>=0;i--)
k[i]=-1.2+i;
Polynomial P(p,3);
Polynomial K(k,4);
cout<<mult4(P,K);
return 0;
}
You have several errors in your code.
You need a copy constructor. Familiarize yourself with The Rule Of Three.
There are many lines where you set the deg of a Polynomial but don't allocate memory for coeff. For example, in shift, you have:
Polynomial shift(Polynomial A, float x)
{
Polynomial c;
int k=0;
c.deg=A.deg+x;
for(int i=c.deg;i>=0;i--)
c.coeff[i]=0;
What you need is:
Polynomial shift(Polynomial A, float x)
{
// Polynomial c(A.deg+x);
// Not sure why you whether c.deg should be A.deg+x or just A.deg.
Polynomial c(A.deg);
int k=0;
for(int i=c.deg;i>=0;i--)
c.coeff[i]=0;
In the operator= function, you are changing the index incorrectly. In stead of using:
for(int i=deg;i>=0;i++) coeff[i] = P.coeff[i];
you need to use:
for(int i=deg;i>=0;i--) coeff[i] = P.coeff[i];
// ^^ Decrement, not increment
In mult4, your use of
p1.deg=((P.deg)/2)-1;
seems flawed. What happens when P.deg/2 is equal to 0? Perhaps you need to use:
p1.deg=(P.deg)/2;
Setting of q1.deg must be similarly updated.
I might have missed other errors.

Invalid allocation runtime error

I have to replicate a vector class using an int and overload a bunch of operators. How ever every time I try to use the +, -, or / operator I get a runtime error which says invalid allocation size: 4294967295 bytes. Any feed back on how I can improve my code is welcome as well.
my code:
myArray.h
#include<iostream>
using namespace std;
class myArray{
private:
int *A;
int lenght;
int maxSize;
public:
myArray(){lenght = 0; maxSize = 0; A = new int[maxSize];}
myArray(int s){maxSize = s; lenght = 0; A = new int[maxSize];}
myArray(const myArray &M);
~myArray(){delete[] A;}
const int getMaxSize(){return maxSize;}
const int getLenght(){return lenght;}
const myArray& operator +(const myArray& A);
const myArray& operator -(const myArray A);
const int operator *(const myArray& A);
const myArray& operator /(const myArray A);
const myArray& operator +(int A);
const myArray& operator -(int A);
const int operator *(int A);
const myArray operator /(int A);
const myArray operator ++();
const myArray operator ++(int);
const myArray operator --();
const myArray operator --(int);
myArray operator -();
int operator [](int ind) const;
myArray& operator =(const myArray& rho);
void push(int n);
int pop();
void insert(int n, int pos);
int remove(int pos);
void resize(int newSize);
};
myException.h
#include<iostream>
#include<exception>
#include<string>
using namespace std;
class myException: public exception
{
private:
int code;
string reason;
public:
myException(){code = 0; reason = "Unknown";}
myException(int c, string r){code = c; reason = r;}
friend ostream& operator <<(ostream& outputStream, const myException A);
};
ostream& operator <<(ostream& outputStream, const myException A)
{
outputStream << "Code: " << A.code << " Reason: " << A.reason << endl;
return outputStream;
}
myArray.cpp
#ifndef MYARRAY_H
#define MYARRAY_H
#include "myArray.h"
#include "myException.h"
//Copy contructor
myArray::myArray(const myArray &M)
{
maxSize = M.maxSize;
lenght = M.lenght;
A = new int[maxSize];
for(int i = 0; i < M.lenght; i++)
A[i] = M.A[i];
}
//Adds the elements of the array with each other and returns the result
const myArray& myArray::operator +(const myArray& secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = A[i] + secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Subtracts the elements of the array with each other and returns the result
const myArray& myArray::operator -(const myArray secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = this->A[i] - secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Gets the dot product of 2 vectors
const int myArray::operator *(const myArray& secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
int result = 0;
for(int i = 0; i < lenght;i++)
result += this->A[i] * secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Divides the elements of the array with each other and returns the result
const myArray& myArray::operator /(const myArray secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = this->A[i] / secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Adds the elements of the array with an int and returns the result
const myArray& myArray::operator +(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] + A;
return result;
}
//Subtracts the elements of the array with an int and returns the result
const myArray& myArray::operator -(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] - A;
return result;
}
//Gets the dot product of a vector multiplied by an int
const int myArray::operator *(int A)
{
int result = 0;
for(int i = 0; i < lenght;i++)
result += this->A[i] * A;
return result;
}
//Divides the elements of the array with an int and returns the result
const myArray myArray::operator /(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] / A;
return result;
}
//increments every element in the array by 1(Pre-increment)
const myArray myArray::operator ++()
{
for(int i = 0; i < lenght; i++)
++A[i];
return *this;
}
//increments every element in the array by 1(Post-increment)
const myArray myArray::operator ++(int)
{
myArray temp(maxSize);
for(int i = 0; i < lenght; i++)
temp.A[i] = A[i]++;
return temp;
}
//decrements every element in the array by 1(Pre-decrement)
const myArray myArray::operator --()
{
for(int i = 0; i < lenght; i++)
--A[i];
return *this;
}
//decrements every element in the array by 1(Post-decrement)
const myArray myArray::operator --(int)
{
myArray temp(maxSize);
for(int i = 0; i < lenght; i++)
temp.A[i] = A[i]--;
return temp;
}
//Makes every element in the array negative
myArray myArray::operator -()
{
for(int i = 0; i < lenght; i++)
A[i] = -A[i];
return *this;
}
//returns the number in the array using []
int myArray::operator [](int ind) const
{
try
{
if(ind > lenght)
throw myException(60, "Array index out of bounds");
return A[ind];
}
catch(myException& e)
{
cout << e;
}
}
//Assignment operator
myArray& myArray::operator=(const myArray& B)
{
delete [] A;
A = new int[B.maxSize];
lenght = B.lenght;
maxSize = B.maxSize;
for(int i = 0; i < B.lenght; i++)
{
A[i] = B.A[i];
}
return (*this);
}
//pushes the value inserted to the next available spot in the array
void myArray::push(int n)
{
try
{
if(lenght == maxSize)
throw myException(30, "Not enough space");
if(lenght == 0)
{
A[0] = n;
lenght++;
}
else
{
for(int i = 0; i < lenght; i++)
{
if(i+1 == lenght)
{
A[i+1] = n;
lenght++;
break;
}
}
}
}
catch(myException& e)
{
cout << e;
}
}
//Removes the last element in the array and returns it
int myArray::pop()
{
try
{
if(lenght <= 0)
throw myException(60, "Array index out of bounds");
int temp = A[lenght - 1];
A[lenght - 1] = NULL;
lenght--;
return temp;
}
catch(myException& e)
{
cout << e;
}
}
inserts an element at the specified position
void myArray::insert(int n, int pos)
{
try
{
if(pos > lenght)
throw myException(60, "Array index out of bounds");
for(int i = 0; i <= lenght; i++)
{
if(i == pos)
{
A[i-1] = n;
}
}
}
catch(myException& e)
{
cout << e;
}
}
//removes an element at a specified position an returns the value.
int myArray::remove(int pos)
{
try
{
if(pos < 0 || (pos > lenght -1))
throw myException(50, "Invalid Position");
int temp = A[pos];
A[pos] = NULL;
for(int i = pos; i < lenght; i++)
{
A[i] = A[i+1];
}
return temp;
}
catch(myException& e)
{
cout << e;
}
}
//Re sizes the entire array
void myArray::resize(int newSize)
{
int *B;
B = new int[newSize];
maxSize = newSize;
for(int i = 0; i < lenght; i++)
B[i] = A[i];
delete[] A;
A = B;
}
#endif
This is just a dummy main to test everything on the myArray class
main.cpp
#include "myArray.h"
int main()
{
int num;
myArray vector1;
myArray vector2(5);
myArray vector3;
vector1.resize(5);
//cout << "Max Size: " << vector1.getMaxSize() << endl;
for(int i = 0; i < 4; i++)
{
cin >> num;
vector1.push(num);
}
for(int i = 0; i < 4; i++)
{
cin >> num;
vector2.push(num);
}
vector3 = vector1 + vector2;
for(int i = 0; i < 4; i++)
cout << vector3.pop() << endl;
}
You create dynamic array with zero size in default constructor.
But in push method you try to set value to it if it's length is zero.
In C++ standard it says:
The effect of dereferencing a pointer returned as a request for zero
size is undefined.
You can only delete it. Fix your push method

= operator for a matrix class behaving weird

CPP
#include "del2.h"
Matrix::Matrix()
{
dArray = NULL;
}
bool Matrix::isValid() const
{
if (dArray == NULL)
return false;
return true;
}
Matrix::~Matrix()
{
delete [] dArray;
}
Matrix::Matrix(unsigned int nRows)
{
rows = nRows;
columns = nRows;
dArray = new double[nRows * nRows];
for (unsigned int i = 0; i < nRows; i++)
{
for (unsigned int n = 0; n < nRows; n++)
{
at(i,n) = 0;
}
}
at(0,0) = 1;
at(rows-1,columns-1) = 1;
}
Matrix::Matrix(unsigned int nRows, unsigned int nColumns)
{
dArray = new double[nRows * nColumns];
rows = nRows;
columns = nColumns;
for (unsigned int i = 0; i < nRows; i++)
for (unsigned int n = 0; n < nColumns; n++)
dArray[i * columns + n] = 0;
}
const Matrix Matrix::operator =(const Matrix & rhs)
{
columns = rhs.getColumns();
rows = rhs.getRows();
delete [] dArray;
dArray = new double[rows * columns];
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
at(row,column) = rhs.at(row,column);
return *this;
}
std::ostream & operator <<( std::ostream & out, const Matrix & classPrint )
{
if (!classPrint.isValid())
return out;
int rows = classPrint.getRows();
int columns = classPrint.getColumns();
out << std::endl;
for (int i = 0; i < rows; i++)
{
out << "| ";
for (int n = 0; n < columns; n++)
out << classPrint.at(i,n) << " ";
out << "|" << std::endl;
}
out << endl;
return out;
}
HEADER:
#ifndef DEL2
#define DEL2
#include <iostream>
using namespace std;
class Matrix
{
private:
int rows;
int columns;
double * dArray;
public:
~Matrix();
Matrix();
explicit Matrix(unsigned int nRows);
Matrix(unsigned int nRows, unsigned int nColumns);
const Matrix operator =(const Matrix & rhs);
const double at(int row, int column) const
{ return dArray[ row*this->columns + column ]; }
double & at( int row, int column )
{ return dArray[ row*this->columns + column ]; }
const int getRows() const {return rows;}
const int getColumns() const {return columns;}
bool isValid() const;
};
std::ostream & operator <<( std::ostream & out, const Matrix & classPrint );
#endif // MATRIX
Main:
#include <iostream>
#include "del2.h"
using namespace std;
int main()
{
Matrix A;
Matrix B(10);
A = B;
cout << A;
return 0;
}
When I run this, the following happens:
The first index, matrix[0] of A, always becomes some weird number like 2.22323e-306. I don't understand why. Even when I try to set "at(0,0) = 1;" in the operator = - function after the loop, it still doesn't have 0.
The problem is here
const Matrix operator =(const Matrix & rhs);
should be
const Matrix& operator =(const Matrix & rhs);
and the definition should be
const Matrix& Matrix::operator =(const Matrix & rhs)
{
if (&rhs == this)
return *this;
Otherwwise operator= is returning a copy of the Matrix which will have dArray same as the original Matrix. Your data will be deleted when the temporary returned array goes out of scope.
Be carefull the operator = is not correct
Matrix & operator = (const Matrix & rhs){
if (&rhs != this){
// Your stuff here
}
return *this;
}
Calling delete [] on a null array is undefined. It can crash.
You must also define the copy constructor