Matrix Overload C++ - c++

In the header file I am suppose to add the declaration of functions which I need to overload operators. Then implement the functions I added into the header file.
Can any one help me with what I am suppose to do? Please explain so I can wrap my head around overloading if possible.
I have listed the code below. As for main I am not suppose to edit it.
Header File
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
public:
Matrix (int sizeX, int sizeY);
~Matrix();
int GetSizeX() const { return dx; }
int GetSizeY() const { return dy; }
long &Element(int x, int y); // return reference to an element
void Print () const;
private:
long **p; // pointer to a pointer to a long integer
int dx, dy;
};
#endif /* MATRIX_H */
Matrix.cpp File
#include <iostream>
#include <cassert>
#include "Matrix.h"
using namespace std;
Matrix::Matrix (int sizeX, int sizeY) : dx(sizeX), dy(sizeY)
{
assert(sizeX > 0 && sizeY > 0);
p = new long*[dx];
// create array of pointers to long integers
assert(p != 0);
for (int i = 0; i < dx; i++)
{ // for each pointer, create array of long integers
p[i] = new long[dy];
assert(p[i] != 0);
for (int j = 0; j < dy; j++)
p[i][j] = 0;
}
}
Matrix::~Matrix()
{
for (int i = 0; i < dx; i++)
delete [] p[i]; // delete arrays of long integers
delete [] p; // delete array of pointers to long
}
long &Matrix::Element(int x, int y)
{
assert(x >= 0 && x < dx && y >= 0 && y < dy);
return p[x][y];
}
void Matrix::Print () const
{
cout << endl;
for (int x = 0; x < dx; x++)
{
for (int y = 0; y < dy; y++)
cout << p[x][y] << "\t";
cout << endl;
}
}
main.cpp
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <ctime>
#include "Matrix.h"
using namespace std;
int main(int argc, char** argv) {
int size1, size2, size3;
const int RANGE = 5; //using to generate random number in the range[1,6]
cout << "Please input three positive integers: (size)";
cin >> size1 >> size2 >> size3;
assert(size1 > 0 && size2 > 0 && size3 > 0);
Matrix myMatrix1(size1, size2), myMatrix2(size2,size3);
Matrix yourMatrix1(size1, size2), yourMatrix2(size2, size3);
Matrix theirMatrix1(size1, size2), theirMatrix2(size1, size3);
srand(time(0));
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
myMatrix1(i,j) = rand() % RANGE + 1;
yourMatrix1 = 2 * myMatrix1;
theirMatrix1 = myMatrix1 + yourMatrix1;
cout << "myMatrix1: " << endl;
cout << myMatrix1 << endl << endl;
cout << "yourMatrix1 = 2 * myMatrix " << endl;
cout << yourMatrix1 << endl << endl;
cout << "myMatrix1 + yourMatrix1: " << endl;
cout << theirMatrix1 << endl << endl;
for (int i = 0; i < size2; i++)
for (int j = 0; j < size3; j++)
myMatrix2(i,j) = rand() % RANGE + 1;
yourMatrix2 = myMatrix2 * 3;
theirMatrix2 = myMatrix1 * yourMatrix2;
cout << "myMatrix1: " << endl;
cout << myMatrix1 << endl << endl;
cout << "myMatrix2: " << endl;
cout << myMatrix2 << endl << endl;
cout << "yourMatrix2 = myMatrix2 * 3 " << endl;
cout << yourMatrix2 << endl << endl;
cout << "myMatrix1 * yourMatrix2: " << endl;
cout << theirMatrix2 << endl << endl;
return 0;
}

You need to look into the main and see what all operators are used with the Matrix objects. You have to overload those operators into the Matrix class given to you i.e. write member functions into this class.
Refer following link for details on operator overloading with examples:
http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading

Related

Vector subscript out of range Visual Studio C++

I'm working with matrices in C++. The task is to find odd numbers in a matrix. I created a function, but when executed with Debug > Start Without Debugging... I get the error:
Debug assertion failed. Expression: vector subscript out of range.
This is my code:
File MatrixVec.h:
#include "MatrixVec.h"
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
MatrixVec::MatrixVec(int rows, int cols, int range)
{
row.assign(cols, 0);
mat.assign(rows, row);
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++){
mat[i][j] = rand() % range;
}
}
}
void MatrixVec::process()
{
int *oddNum = new int(mat[0].size());
for (int i = 0; i < mat[0].size(); i++) {
oddNum[i] = 0;
}
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++) {
oddNum[j] += mat[i][j] % 2;
}
}
for (int i = 0; i < mat[0].size(); i++) {
cout << i + 1 << ". kolona " << oddNum[i]<< " neparnih elemenata." << endl;
}
//Edit
delete[] oddNum; //forgot this line
}
File MatrixVec.h:
#include "Matrix.h"
#include <vector>
class MatrixVec : public Matrix {
public:
MatrixVec(int rows, int cols, int range);
void print();
void process();
private:
std::vector<int> row;
std::vector<std::vector<int> > mat;
};
File Matrix.h:
class Matrix {
public:
virtual void print() = 0;
virtual void process() = 0;
};
File main.cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include "Matrix1D.h"
#include "Matrix2D.h"
#include "MatrixVec.h"
using namespace std;
#define NUMBER_RANGE 10
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "Niste uneli potrebne argumente za pokretanje programa!" << endl;
cout << "Argumenti komandne linije treba da budu:" << endl;
cout << "1. N dimenzija matrice" << endl;
cout << "2. M dimenzija matrice" << endl;
exit(-1);
}
// inicijalizacija generatora nasumičnih brojeva
srand(unsigned int(time(NULL)));
int rowNum = atoi(argv[1]);
int colNum = atoi(argv[2]);
// a)
cout << endl << endl << "a) Matrix 1D representation" << endl;
Matrix1D mat1(rowNum, colNum, 10);
mat1.print();
mat1.process();
//b)
cout << endl << endl << "b) Matrix 2D representation" << endl;
Matrix2D mat2(rowNum, colNum, 10);
mat2.print();
mat2.process();
//c)
cout << endl << endl << "c) Matrix vector of vector representation" << endl;
MatrixVec mat3(rowNum, colNum, 10);
mat3.print();
mat3.process();
return 0;
}
This line int *oddNum = new int(mat[0].size()); actually creating one int with value of mat[0].size(). You want something like this to create an array of size mat[0].size().
int *oddNum = new int[mat[0].size()];
Note: This still not answer the exact error. Seems like your mat vector is empty.

Heap sort and insertion sort

I want to make a c++ program that runs two algorithms - insertion and heap sort. But I keep getting an error that array size must have integral or enumeration type, not double. Where are my mistakes? I'm reading data from file.
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
void sortInsertion(double A[], int N);
void heapSort(double A[], int N);
void heapify(double A[], int N, int i);
using namespace std;
double *Data;
double* A;
double* B;
double* A1;
double* B1;
double N;
unsigned long int palyginimai1 = 0;
unsigned long int priskyrimai1 = 0;
unsigned long int palyginimai2 = 0;
unsigned long int priskyrimai2 = 0;
int main()
{
srand(time(NULL));
cout << "generuojame atsitktinius duomenis ..." << endl;
generuoti(106000, "duom.txt");
cout << "nuskaitome duomenis ..." << endl;
nuskaityti("duom.txt");
A = new double[N];
B = new double[N];
A1 = new double[N];
B1 = new double[N];
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
//cout << "Heap array:" << endl;
for (int i = 0; i < N; i++)
//cout << A[i] << " ";
//cout << endl;
//cout << "Insertion array: " << endl;
for (int i = 0; i < N; i++)
{
B[i] = A[i];
//cout << B[i] << " ";
}
for (int i = 0; i < N; i++)
{
A1[i] = A[i];
B1[i] = B[i];
}
//cout << endl;
int nUntil = 2000;
while (nUntil <= 106000)
{
sortInsertion(B1, nUntil);
heapSort(A1, nUntil);
cout << priskyrimai1 << endl;
nUntil = nUntil * 2;
for (int i = 0; i < N; i++)
{
A1[i] = A[i];
B1[i] = B[i];
}
//cout << nUntil << palyginimai2 << " " << priskyrimai2 << endl;
}
/*cout << "Surusiuota skaiciu seka Heap:" << endl;
for (int i = 0; i < N; i++)
cout << A1[i] << " ";
cout << endl;
cout << "Surusiuota skaiciu seka Insertion:" << endl;
for (int i = 0; i < N; i++)
cout << B1[i] << " ";
cout << endl;*/
system("pause");
return 0;
}
void generuoti(int _N, const char *_file) {
ofstream os(_file);
os << _N << endl;
for (int i = 0; i < _N; i++)
{
os << " " << (double)(rand() % 1001) / (double)1000;
}
//os << " " << (double)13 << " " << (double)18 << " " << (double)25 << " " << (double)2 << " " << (double)6 << " " << (double)11 << " " << (double)16 << " " << (double)1 << " " << (double)6 << " " << (double)21 << " " << (double)17;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
void sortInsertion(double A[], int N) {
double temp;
int hole;
for (int i = 1; i < N; i++)
{
palyginimai1++;
temp = A[i];
hole = i;
while (hole > 0 && A[hole - 1] > temp)
{
palyginimai1++;
A[hole] = A[hole - 1];
priskyrimai1++;
hole--;
}
priskyrimai1++;
A[hole] = temp;
}
}
void heapify(double A[], int N, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
priskyrimai2 = priskyrimai2 + 3;
if (l < N && A[l] > A[largest])
{
largest = l;
priskyrimai2++;
}
if (r < N && A[r] > A[largest])
{
largest = r;
priskyrimai2++;
}
if (largest != i)
{
swap(A[i], A[largest]);
heapify(A, N, largest);
palyginimai2++;
priskyrimai2++;
}
}
void heapSort(double A[], int N)
{
for (int i = N / 2 - 1; i >= 0; i--)
{
heapify(A, N, i);
palyginimai2++;
}
for (int i = N - 1; i >= 0; i--)
{
swap(A[0], A[i]);
priskyrimai2++;
heapify(A, i, 0);
palyginimai2++;
}
}
Also, I'm counting palyginimai - comparisons, priskyrimai-assignments.
A quick solution would be to replace anywhere you use the subscript([]) operator do this instead: A = new double[(int)N];
I hope this helps.

C++ Parallel Arrays

In this Parallel Array I can not see or figure out why I am printing the memory address instead of the values Entered. I ask the C++ gods to enlighten me and Point me to some good tutorials about this issue so that I can learn from. Code is below.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ios>
using namespace std;
// Assign a constant
const int rowSize = 6;
const int columnSize = 4;
void displayWelcome()
{
cout << "\tCorporation X\n";
cout << "Quartily Reports for the six Entities\n";
cout << "Showing you the Highest Average out of the six\n";
cout << endl;
}
// Assign Words in a row of 6
string* entitiesArray(string(entities)[rowSize])
{
string entitiesName[rowSize] = {"East ","West ","Central ","Midwest"
,"South ","South East "};
//string entitiesName;
for(int i=0; i < rowSize; i++)
{
cout << entitiesName[i] << endl;
}
return entitiesName;
}
// Assign numbers to a 6x4
double* entriesArray(double(corpArray)[rowSize][columnSize])
{
// Assign Random Numbers to the Array
srand(time(0));
double rowSum = 0.0, average = 0.0;
for (int r = 0; r < rowSize; ++r)
{
rowSum = 0;
for (int c = 0; c < columnSize; ++c)
{
corpArray[r][c] = rand() % 101;
cout << setw(5) << left << corpArray[r][c] << " ";
rowSum += corpArray[r][c];
average = rowSum / 4;
}
cout << average;
cout << endl;
}
return 0;
}
// Parallel Array This is where is prints the Memory Address
void pArray(string &theEntitiesArray,double &theEntriesArray)
{
string entity = &theEntitiesArray;
double entry = &theEntriesArray;
for(int row_index = 0; row_index < 6; row_index++)
{
cout << setw(10) << entity <<endl;
for (int col_index = 0; col_index < 4; col_index++)
{
cout << setw(10) << entry << endl;
}
}
}
int main(int argc, const char * argv[])
{
// Declare an Array & Variables
double corpArray[rowSize][columnSize];
string entities[rowSize];
double* theEntriesArray;
string* theEntitiesArray;
char parallelArray;
displayWelcome();
theEntitiesArray = entitiesArray(entities);
theEntriesArray = entriesArray(corpArray);
pArray(*theEntitiesArray, *theEntriesArray);
cout << endl;
return 0;
}
#JSF beat me to it in a comment, but in the line double entry = &theEntriesArray;, you're assigning the address of theEntriesArray to the variable entry, rather than the numerical value it refers to. Change it to:
double entry = theEntriesArray;
You have Some Problems in Functions which initzlize the array now its fine try to read about pointer
1- http://www.cplusplus.com/doc/tutorial/pointers/
2- http://www.tutorialspoint.com/cplusplus/cpp_pointer_to_pointer.htm
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ios>
using namespace std;
// Assign a constant
const int rowSize = 6;
const int columnSize = 4;
void displayWelcome()
{
cout << "\tCorporation X\n";
cout << "Quartily Reports for the six Entities\n";
cout << "Showing you the Highest Average out of the six\n";
cout << endl;
}
// Assign Words in a row of 6
string* entitiesArray(string(entities)[rowSize])
{
string* entitiesName = new string[rowSize];
string temp[]= { "East ", "West ", "Central ", "Midwest"
, "South ", "South East " };
for (int i = 0; i < rowSize; i++)
{
entitiesName[i] = temp[i];
}
//string entitiesName;
for (int i = 0; i < rowSize; i++)
{
cout << entitiesName[i] << endl;
}
return entitiesName;
}
// Assign numbers to a 6x4
double** entriesArray(double(corpArray)[rowSize][columnSize])
{
double** tempcorpArray = new double*[rowSize];// [columnSize];
for (int i = 0; i < rowSize; ++i)
{
tempcorpArray[i] = new double[columnSize];
}
// Assign Random Numbers to the Array
srand(time(0));
double rowSum = 0.0, average = 0.0;
for (int r = 0; r < rowSize; ++r)
{
rowSum = 0;
for (int c = 0; c < columnSize; ++c)
{
tempcorpArray[r][c] = rand() % 101;
cout << setw(5) << left << tempcorpArray[r][c] << " ";
rowSum += tempcorpArray[r][c];
average = rowSum / 4;
}
cout << average;
cout << endl;
}
return tempcorpArray;
}
// Parallel Array This is where is prints the Memory Address
void pArray(string* theEntitiesArray, double** theEntriesArray )
{
string* entity = theEntitiesArray;
double** entry = theEntriesArray;
for (int row_index = 0; row_index < 6; row_index++)
{
cout << setw(10) << (entity[row_index]) << endl;
for (int col_index = 0; col_index < 4; col_index++)
{
cout << setw(10) << (entry[row_index][col_index]) << endl;
}
}
}
int main(int argc, const char * argv[])
{
// Declare an Array & Variables
double corpArray[rowSize][columnSize];
string entities[rowSize];
char parallelArray;
displayWelcome();
string* theEntitiesArray = entitiesArray(entities);
double** theEntriesArray = entriesArray(corpArray);
pArray(theEntitiesArray, theEntriesArray);
cout << endl;
return 0;
}
if there is any problem feel free to ask :D

Merge Sort Iterative Issue

I have searched many examples and have yet to be able to find where exactly my problem lies. I am trying to implement the merge sort algorithm from the Cormen intro to algorithms book-- here is where I am at so far-- I have tried throwing in print statements to follow how the arrays are getting rebuilt but I am not seeing it... can anyone help?
Code:
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int p = 0;
int q = 0;
int r = 0;
int getRandom()
{
int randNum = 0;
randNum = 1 + rand() % 100;
return randNum;
}
void populateArray(int * array, int size)
{
for (int i = 0; i < size; i++) {
array[i]=getRandom();
}
}
void merge (int * array, int p, int q, int r) // p = start, q = mid, r = end
{
int i = 0; // left array iterator
int j = 0; // right array iterator
int n1 = q - p + 1;
int n2 = r - q;
// int arrayL[n1 + 1];
//int arrayR[n2 + 1];
int arrayL[n1];
int arrayR[n2];
for (i = 0; i < n1; i++) {
arrayL[i] = array[p + i];
}
cout << "TEST ARRAY MS A: ";
for (int count = 0; count < n1; count++) {
cout << arrayL[count] << " ";
}
cout << endl << endl;
for (j = 0; j < n2; j++) {
arrayR[j] = array[q + j + 1];
}
cout << "TEST ARRAY MS B: ";
for (int count = 0; count < n2; count++) {
cout << arrayR[count] << " ";
}
cout << endl << endl;
//arrayL[n1 + 1] = 1000;
//arrayR[n2 + 1] = 1000;
//i = 0;
//j = 0;
for (int k = p, i = j = 0; k <= r; k++) {
if (j >= n2 || (i <= n1 && arrayL[i] <= arrayR[j])) {
array[k] = arrayL[i];
i++;
cout << "TEST ARRAY in loop A: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
else {
array[k] = arrayR[j];
j++;
cout << "TEST ARRAY in loop B: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
cout << "TEST ARRAY in loop: ";
for (int tempIt = 0; tempIt < r; tempIt++) {
cout << array[tempIt] << " ";
}
cout << endl << endl;
}
}
void mergeSort (int * array, int p, int r)
{
if (p < r) {
q = floor((p + r) / 2);
mergeSort(array, p, q);
mergeSort(array, q + 1, r);
merge(array, p, q, r);
}
}
int main(int argc, const char * argv[])
{
unsigned seed = time(0);
srand(seed);
int testArray[5];
populateArray(testArray, 5);
cout << "TEST ARRAY: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
mergeSort(testArray, 0, 4);
cout << "TEST ARRAY after mergeSort: ";
for (int count = 0; count < 5; count++) {
cout << testArray[count] << " ";
}
cout << endl << endl;
return 0;
}

Why isnt my simpleVector.cpp linking? (starting out with c++)

i got the .cpp and .h straight from the book, it seems as if nothing is missing, but im getting these linking errors....
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <new> // needed for bad__alloc exception
#include <cstdlib> // needed for the exit function
using namespace std;
template <class T>
class simplevector
{
private:
T *aptr;
int arraysize;
void memerror(); // handles mem aloc errors
void suberror(); // handles subscripts out of range
public:
simplevector() // default constructor
{ aptr = 0; arraysize = 0; }
simplevector(int); // constructor
simplevector(const simplevector &); // coppy constructor
~simplevector();
int size()
{ return arraysize; }
T &operator[](const int &); // overloaded [] operator
};
template <class T>
simplevector<T>::simplevector(int s)
{
arraysize = s;
// allocate memory for the array
try
{
aptr = new T [s];
}
catch (bad_alloc)
{
memerror();
}
// initialize the array.
for (int count = 0; count < arraysize; count++)
*(aptr + count) = 0;
}
template <class T>
simplevector<T>::simplevector(const simplevector &obj)
{
arraysize = obj.arraysize;
aptr = new T [arraysize];
if (aptr == 0)
memerror();
for(int count = 0; count < arraysize; count++)
*(aptr + count) = *(obj.aptr + count);
}
template <class T>
simplevector<T>::~simplevector()
{
if (arraysize > 0)
delete [] aptr;
}
template <class T>
void simplevector<T>::memerror()
{
cout << "ERROR: Cannot allocate memory.\n";
exit(0);
}
template <class T>
T &simplevector<T>::operator [](const int &sub)
{
if (sub < 0 || sub >= arraysize)
suberror();
return aptr[sub];
}
#endif
This program demonstrates the simplevector template:
#include <iostream>
#include "simplevector.h"
using namespace std;
int main()
{
simplevector<int> inttable(10);
simplevector<float> floattable(10);
int x;
//store values in the arrays.
for (x = 0; x < 10; x++)
{
inttable[x] = (x * 2);
floattable[x] = (x * 2.14);
}
//display the values in the arrays.
cout << "these values are in inttable:\n";
for (x = 0; x< 10; x++)
cout << inttable[x] << " ";
cout << endl;
cout << "these values are in floattable:\n";
for (x = 0; x< 10; x++)
cout << floattable[x] << " ";
cout << endl;
//use the standard + operator on array elements.
cout << "\nAdding 5 to each element of inttable"
<< " and floattable.\n";
for (x = 0; x< 10; x++)
{
inttable[x] = inttable[x] + 5;
floattable[x] = floattable[x] + 1.5;
}
//display the values in the array.
cout << "These values are in inttable:\n";
for (x = 0; x< 10; x++)
cout << inttable[x] << " ";
cout << endl;
cout << "These values are in floattable:\n";
for (x = 0; x< 10; x++)
cout << floattable[x] << " ";
cout << endl;
// use the standard ++ operator on array elements.
cout << "\nIncrementing each element of inttable and"
<< " floattable.\n";
for (x = 0; x< 10; x++)
{
inttable[x]++;
floattable[x]++;
}
//display the values in the array.
cout << "These values are in inttable:\n";
for (x = 0; x< 10; x++)
cout << inttable[x] << " ";
cout << endl;
cout << "These values are in floattable:\n";
for (x = 0; x< 10; x++)
cout << floattable[x] << " ";
cout << endl;
return 0;
}
It's right there in the errors you posted in the OP comments - you declared simplevector::suberror without ever defining it.
Where are the guts of suberror()? I don't see that in the class implementation.