implement copy constructor c++ Polynomial and Rational - c++

I need some help to understand how to implement the constructor in the Rational class.
I try to send the numerator(p1) and denominator(p2) by reference to the rational class however it start both of them to "0" and not copy them.
the idea is to create rational that contain two Polynomial (numerator and denominator) and print them.
I didn't add all the code just what I think is relevant.
class Polynomial
{
private:
double *varibles;
static int degree;
public:
Polynomial(double * var = NULL, static int deg = NULL);
Polynomial(static int deg );
};
class Rational
{
private:
Polynomial numerator;
Polynomial denominator;
public:
Rational(const Polynomial& p1 , const Polynomial & p2 );
cpp file
Rational::Rational(const Polynomial& p1 , const Polynomial & p2 )
{
this->numerator = p1;
this->denominator = p2;
}
Polynomial::Polynomial(double * var, static int deg) {
if (deg < (sizeof(var) / sizeof(double)))
var = (double*)realloc(var, deg * sizeof(double));
this -> degree = deg;
this -> varibles = var;
}
Polynomial::Polynomial(static int deg) {
this->degree = deg;
this->varibles = (double*)calloc(deg, sizeof(double));
}
void Polynomial::setCoeff(int index, double num) {
if (!this->degree)
Polynomial(index);
this->varibles[index] = num;
}
void Polynomial::SetPolynomial(Polynomial& p) {
int size = p.degree;
int i;
for (i = 0; i < size; i++) {
cout << "Enter Number for X^ " << i+1 << " varibles" << endl;
cin >> p.varibles[i];
}
}
double Polynomial::getDegree(bool what) const {
if (what == false)
return this->degree;
else
return 0;
}
double Polynomial::getCoeff(int index) const {
return this->varibles[index];
}
int Polynomial::getMaxDegree() {
return degree;
}
void Polynomial::print() {
int size = this->degree ; // -1 ?
int i;
if (!this->degree)
cout << "Polynomial = 0";
else {
while (this->varibles[size] == 0)
size--;
if (size < 1 && this->varibles[0] == 0) {
cout << "Polynomial = 0";
}
else {
for (i = 0; i < size; i++) {
if (i == 0)
cout << this->varibles[i] << "+";
else
cout << this->varibles[i] << "X^" << i << "+";
}
cout << this->varibles[i] << "X^" << i ;
}
}
cout << endl;
}
main / test
void testRational() {
Rational r1;
r1.print();
double c[] = { 0,2,2,3,4,5 };
Polynomial p1(c, 5);
p1.print();
c[0] = 1.2;
Polynomial p2(c, 3);
Rational r2(p1, p2);
cout << "test8" << endl;
r2.print();

Related

How to pass an array to a class?

#include <iostream>
#include <string>
using namespace std;
class Term;
class Polynomial;
class Term {
public:
friend class Polynomial;
void set_term(string s);
int get_pow();
int get_coefficient();
private:
int coefficient;
int pow;
};
class Polynomial {
public:
friend class Term;
Polynomial(int s, Term t[]);
int get_size();
Term *myterm;
private:
int P_size;
};
void Term::set_term(string s) {
coefficient = stoi(s.substr(1, 1));
pow = stoi(s.substr(4, 1));
if (s[0] == '-') {
coefficient = -coefficient;
}
}
int Term::get_coefficient() { return coefficient; }
int Term::get_pow() { return pow; }
Polynomial::Polynomial(int s, Term t[]) {
P_size = s;
myterm = new Term[s];
for (int i = 0; i < s; i++) {
myterm[i].coefficient = t[i].coefficient;
cout << i << " Term " << t[i].coefficient << endl;
cout << i << " Polynomial " << myterm[i].coefficient << endl;
myterm[i].pow = t[i].pow;
}
}
Polynomial::get_size() { return P_size; }
int main() {
string x1;
cin >> x1;
int size_x1 = x1.size();
Term term1[size_x1];
for (int i = 0; i < size_x1; i += 5) {
term1[i].set_term(x1.substr(i, 5));
}
Polynomial p1(size_x1 / 5, term1);
for (int i = 0; i < size_x1; i += 5) {
cout << term1[i].get_coefficient() << "x^";
cout << term1[i].get_pow() << endl;
}
cout << "------------------" << endl;
for (int i = 0; i < p1.get_size(); i++) {
if (p1.myterm[i].get_coefficient() > 0)
cout << "+";
cout << p1.myterm[i].get_coefficient();
cout << "x^";
cout << p1.myterm[i].get_pow() << endl;
}
return 0;
}
term1 in main is working right but when I pass it to p1(Polynomial) just t[0] and, myterm[0]
is true I mean I pass term1 to p1 as t so t[0] = term1[0] and myterm[0] = t[0]
Polynomial::Polynomial(int s, Term t[]) {
P_size = s;
myterm = new Term[s];
for (int i = 0; i < s; i++) {
myterm[i].coefficient = t[i].coefficient;
cout << i << " Term " << t[i].coefficient << endl;
cout << i << " Polynomial " << myterm[i].coefficient << endl;
myterm[i].pow = t[i].pow;
}
}
in Polynomial constructor both t[1].coeffient and, myterm[1].coefficient are 4941660(for instance)
however, t is term1 and in term1 term1[1] is the 4(for instance)
if term1[1] is 4 so t[1] should be 4 but it's not so myterm[1], is not 4 too.
There's a lot of confusion over sizes here
string x1;
cin >> x1;
int size_x1 = x1.size();
Term term1[size_x1];
for (int i = 0; i < size_x1; i += 5) {
term1[i].set_term(x1.substr(i, 5));
}
Polynomial p1(size_x1 / 5, term1);
You didn't say what your input is, but suppose it is "1234567890" then size_x1 equals 10, so term1 will also have size 10. Then your for loop will execute twice, with i equal to 0 and i equal to 5, so you will assign 12345 to term1[0] and 67890 to term1[5]. That makes no sense to me. term1 has size 10 but the only elements assigned to are zero and five.
Then you create p1 with size size_x1/5 which equals 2. So the constructor for p1 will look at term1[0] and term1[1], but in the for loop you assigned to term1[0] and term1[5].
You have to think carefully about what the code you are writing is actually doing. The compiler will do exactly what you tell it to. It's not like talking to a person who can understand what you really meant. So you have to be very careful. This is I think you really meant (but I could be wrong)
string x1;
cin >> x1;
int size_x1 = x1.size();
int size_term1 = size_x1/5;
Term term1[size_term1];
for (int i = 0; i < size_term1 ; ++i) {
term1[i].set_term(x1.substr(5*i, 5));
}
Polynomial p1(size_term1, term1);
I created a new variable size_term1 with the size of the term array, which is now the sizeof the input divided by 5. And I changed the for loop so that it assigns to term1[0] and term1[1].
So your problem has nothing to do with passing an array to a class, which you did perfectly correctly. It was not thinking clearly about the code you were writing, and making mistakes in the logic.

Virtual function doesnt work correctly

I need to write a program using virtual function of addition and inheritance.
i wrote this 3 classes, but my virtual function doesnt display the result.
it should write the summ of decimal de("10004") and decimal deci("12"); but it just displays Array->
how can i possibly fix this?
#include <string>
#include <iostream>
#include <cassert>
using namespace std;
int rev(int);
class Array
{
private:
string arr[100];
size_t size;
string str;
public:
Array();
Array(string s)
{
str = s;
cout << str << endl;
}
/*{
cin >> size;
for (int i = size - 1; i >= 0; i--)
{
arr[i] = '0';
cout << arr[i];
}
cout << endl;
}*/
string& operator[] (const int index);
Array operator +(Array ar)
{
int x = stoi(str);
int y = stoi(ar.str);
int d = x + y;
string s = to_string(d);
return s;
}
virtual void plus( Array *b)
{
cout << "Array -> " << str + b->str << endl;
}
};
string& Array::operator[] (const int index)
{
assert(index >= 0 && index < size);
return arr[index];
}
class decimal : public Array
{
private:
unsigned char dec[100];
size_t size;
public:
decimal() : size{ 0 } {}
decimal(const char* get)
{
size = strlen(get);
for (int i = size - 1; i >= 0; i--, get++)
{
dec[i] = *get;
cout << dec[i];
}
cout << endl;
}
void plus(decimal* b);
friend decimal operator + (decimal const &, decimal const &);
friend decimal operator - (decimal const &, decimal const &);
friend decimal operator * (decimal const &, decimal const &);
friend decimal operator / (decimal const &, decimal const &);
friend decimal operator % (decimal const &, decimal const &);
};
decimal operator + (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) + rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator - (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) - rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator * (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) * rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator / (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) / rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator % (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) % rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
void decimal::plus( decimal* b)
{
cout << "Array -> " << atoi((char*)dec) + atoi((char *)b->dec) << endl;
}
int rev(int n)
{
int r = 0, remainder;
while (n != 0)
{
remainder = n % 10;
r = r * 10 + remainder;
n /= 10;
}
return r;
}
class BitString : public Array
{
char *string;
public:
BitString() = default;
BitString(char *str)
{
string = new char[strlen(str) + 1]; strcpy_s(string, strlen(str) + 1, str);
}
void operator ~()
{
for (int i = 0; i<strlen(string); i++)
string[i] == '1' ? string[i] = '0' : string[i] = '1';
}
void operator &(BitString a)
{
if (strlen(string) != strlen(a.string))
cout << "Different lengths" << endl;
else
{
for (int i = 0; i<strlen(a.string); i++)
if (string[i] == '1' && a.string[i] == '1')
string[i] = '1';
else
string[i] = '0';
}
}
void operator +(BitString a)
{
if (strlen(string) != strlen(a.string))
cout << "Different lengths" << endl;
else
{
for (int i = 0; i<strlen(a.string); i++)
if (string[i] == '1' || a.string[i] == '1')
string[i] = '1';
else
string[i] = '0';
}
for (int i = 0; i < strlen(string); i++)
cout << string[i];
cout << endl;
}
void operator ^(BitString a)
{
if (strlen(string) != strlen(a.string))
cout << "Different lengths";
else
{
for (int i = 0; i<strlen(a.string); i++)
if ((string[i] == '1' && a.string[i] == '0') || (string[i] == '0' && a.string[i] == '1'))
string[i] = '1';
else
string[i] = '0';
}
}
void Show()
{
cout << string << endl;
}
void plus(BitString *b)
{
cout << "bitstring -> " << atoi(string) + atoi(b->string) << endl;
}
};
int main()
{
int a;
char str[80];
Array *arr;
Array *arr1;
BitString obj("1010101");
BitString obj1("1110001");
decimal de("10004");
decimal deci("12");
arr = &de;
arr1 = &deci;
arr->plus(arr1);
system("Pause");
}
EDIT:
#include <string>
#include <iostream>
#include <cassert>
using namespace std;
int rev(int);
class Array
{
public:
string arr[100];
size_t size;
string str;
public:
Array() { };
Array(string s)
{
str = s;
cout << str << endl;
}
string& operator[] (const int index);
Array operator +(Array ar)
{
int x = stoi(str);
int y = stoi(ar.str);
int d = x + y;
string s = to_string(d);
return s;
}
virtual void plus(Array *b)
{
cout << "Array -> " << str + b->str << endl;
}
};
string& Array::operator[] (const int index)
{
assert(index >= 0 && index < size);
return arr[index];
}
class decimal : public Array
{
private:
unsigned char dec[100];
size_t size;
public:
decimal() : size{ 0 } {}
decimal(const char* get)
{
size = strlen(get);
for (int i = size - 1; i >= 0; i--, get++)
{
dec[i] = *get;
cout << dec[i];
}
cout << endl;
}
void plus(Array* b);
friend decimal operator + (decimal const &, decimal const &);
friend decimal operator - (decimal const &, decimal const &);
friend decimal operator * (decimal const &, decimal const &);
friend decimal operator / (decimal const &, decimal const &);
friend decimal operator % (decimal const &, decimal const &);
};
decimal operator + (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) + rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator - (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) - rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator * (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) * rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator / (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) / rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
decimal operator % (decimal const &a, decimal const &b)
{
int x = atoi((char *)a.dec);
int y = atoi((char *)b.dec);
int d = rev(x) % rev(y);
string s = to_string(d);
return decimal(s.c_str());
}
void decimal::plus(Array* b)
{
cout << "Array -> " << atoi((char*)dec) + stoi(b->str) << endl;
}
int rev(int n)
{
int r = 0, remainder;
while (n != 0)
{
remainder = n % 10;
r = r * 10 + remainder;
n /= 10;
}
return r;
}
class BitString : public Array
{
char *string;
public:
BitString() = default;
BitString(char *str)
{
string = new char[strlen(str) + 1]; strcpy_s(string, strlen(str) + 1, str);
}
void operator ~()
{
for (int i = 0; i<strlen(string); i++)
string[i] == '1' ? string[i] = '0' : string[i] = '1';
}
void operator &(BitString a)
{
if (strlen(string) != strlen(a.string))
cout << "Different lengths" << endl;
else
{
for (int i = 0; i<strlen(a.string); i++)
if (string[i] == '1' && a.string[i] == '1')
string[i] = '1';
else
string[i] = '0';
}
}
void operator +(BitString a)
{
if (strlen(string) != strlen(a.string))
cout << "Different lengths" << endl;
else
{
for (int i = 0; i<strlen(a.string); i++)
if (string[i] == '1' || a.string[i] == '1')
string[i] = '1';
else
string[i] = '0';
}
for (int i = 0; i < strlen(string); i++)
cout << string[i];
cout << endl;
}
void operator ^(BitString a)
{
if (strlen(string) != strlen(a.string))
cout << "Different lengths";
else
{
for (int i = 0; i<strlen(a.string); i++)
if ((string[i] == '1' && a.string[i] == '0') || (string[i] == '0' && a.string[i] == '1'))
string[i] = '1';
else
string[i] = '0';
}
}
void Show()
{
cout << string << endl;
}
void plus(Array *b)
{
cout << "bitstring -> " << atoi(string) + stoi(b->str) << endl;
}
};
int main()
{
int a;
char str[80];
Array *arr;
Array *arr1;
BitString obj("1010101");
BitString obj1("1110001");
decimal de("10004");
decimal deci("12");
arr = &de;
arr1 = &deci;
arr->plus(arr1);
arr = &obj;
arr1 = &obj1;
arr->plus(arr1);
system("Pause");
}
Try to replace variable named string in BitString. It is defined type from <string> library in namespace std and you use it with using namespace std; There is a confusion with naming. For example I renamed string to stringMine in this example:
class BitString : public Array
{
char *stringMine;
public:
BitString() = default;
BitString(char *str)
{
stringMine = new char[strlen(str) + 1]; strcpy_s(stringMine, strlen(str) + 1, str);
}
void operator ~()
{
for (int i = 0; i<strlen(stringMine); i++)
stringMine[i] == '1' ? stringMine[i] = '0' : stringMine[i] = '1';
}
void operator &(BitString a)
{
if (strlen(stringMine) != strlen(a.stringMine))
cout << "Different lengths" << endl;
else
{
for (int i = 0; i<strlen(a.stringMine); i++)
if (stringMine[i] == '1' && a.stringMine[i] == '1')
stringMine[i] = '1';
else
stringMine[i] = '0';
}
}
void operator +(BitString a)
{
if (strlen(stringMine) != strlen(a.stringMine))
cout << "Different lengths" << endl;
else
{
for (int i = 0; i<strlen(a.stringMine); i++)
if (stringMine[i] == '1' || a.stringMine[i] == '1')
stringMine[i] = '1';
else
stringMine[i] = '0';
}
for (int i = 0; i < strlen(stringMine); i++)
cout << stringMine[i];
cout << endl;
}
void operator ^(BitString a)
{
if (strlen(stringMine) != strlen(a.stringMine))
cout << "Different lengths";
else
{
for (int i = 0; i<strlen(a.stringMine); i++)
if ((stringMine[i] == '1' && a.stringMine[i] == '0') || (stringMine[i] == '0' && a.stringMine[i] == '1'))
stringMine[i] = '1';
else
stringMine[i] = '0';
}
}
void Show()
{
cout << stringMine << endl;
}
void plus(BitString *b)
{
cout << "bitstring -> " << atoi(stringMine) + atoi(b->stringMine) << endl;
}
};
Also you need to override void plus(Array *b) correctly
void decimal::plus( decimal* b); doesn't override it is a new function, it must be
void decimal::plus( Array* b)
to override. Or for good syntax:
virtual void decimal::plus( Array* b) override
Also about BitString method, right way to override is to:
virtual void plus(Array *b) override
{
cout << "bitstring -> " << atoi(stringMine) + atoi(b->stringMine) << endl;
}
But after all you will be need to declare two variables in base class to fix compile errors:
class Array
{
public:
char *stringMine;
unsigned char dec[100];
You call these variables in derived classes from base class.
Your parameter types are different, you are not overriding in derived classes but simply hiding the base class definition.
It should say
class decimal : public Array
{
public:
void plus(Array* b);
};
class BitString : public Array
{
public:
void plus(Array* b);
};

Bubble array sort in C++ implementation

I'm trying to get this code to sort names but it doesn't seem to work for me. What could be wrong? I have a class named Student and want to pass the names and sort them in ascending order. So what I am trying to do is pass the 4 object firstname onto the the sort_list function and sort them in ascending order and display them afterwards. However when I run the code it shows me the same order I had and the sort function didn't seem to have done anything. See if you guys can help me out here.
#include <iostream>
#include<string>
using namespace std;
//***************************************************************************
//STUDENT CLASS
//***************************************************************************
class Student
{
private:
string firstname;
string lastname;
string studentID;
string phoneNumber;
double gpa;
public:
Student();
Student(const string&, const string&, const string&, const string&, const double&);
string getfirstName() const;
string getlastName() const;
string getstudentId() const;
string getphoneNumber() const;
double getGPA() const;
void setfirstName(string&);
void setlastName(string&);
void setstudentId(string&);
void setphoneNumber(string&);
void setGAP(double&);
};
Student::Student()
{
firstname = " ";
lastname = " ";
studentID = " ";
phoneNumber = " ";
gpa = 0;
}
Student::Student(const string&a, const string&b, const string&c, const string&d, const double&e)
{
firstname = a;
lastname = b;
studentID = c;
phoneNumber = d;
gpa = e;
}
string Student::getfirstName()const
{
return firstname;
}
string Student::getlastName()const
{
return lastname;
}
string Student::getstudentId() const
{
return studentID;
}
string Student::getphoneNumber() const
{
return phoneNumber;
}
double Student::getGPA() const
{
return gpa;
}
void Student::setfirstName(string&u)
{
firstname = u;
}
void Student::setlastName(string&v)
{
lastname = v;
}
void Student::setstudentId(string&x)
{
studentID = x;
}
void Student::setphoneNumber(string&y)
{
phoneNumber = y;
}
void Student::setGAP(double&z)
{
gpa = z;
}
//***************************************************************************
//COURSE CLASS
//***************************************************************************
class Course :public Student
{
private:
string code;
int section;
int capacity;
int numStudents;
Student *list;
public:
Course();
Course(string, int, int);
~Course();
string getCourseCode();
int getSection();
int getCapacity();
int getNumStudents();
void setCourseCode(string);
void setSection(int);
void add(const Student&);
void display();
void display(const string, const int);
void remove(const string m, const int n);
void sort_list();
};
Course::Course()
{
code = "CMPT1020";
section = 1;
capacity = 35;
numStudents = 0;
list = new Student[35];
}
Course::Course(string a, int b, int c)
{
code = a;
section = b;
capacity = c;
numStudents = 0;
list = new Student[c];
}
Course::~Course()
{
delete[] list;
list = nullptr;
}
string Course::getCourseCode()
{
return code;
}
int Course::getSection()
{
return section;
}
int Course::getCapacity()
{
return capacity;
}
int Course::getNumStudents()
{
return numStudents;
}
void Course::setCourseCode(string a)
{
code = a;
}
void Course::setSection(int b)
{
section = b;
}
void Course::add(const Student& s)
{
if (numStudents == capacity)
{
cout << "Course is full" << endl;
return;
}
list[numStudents] = s;
numStudents++;
int i = numStudents - 2;
while (i >= 0 && (s.getGPA() > list[i].getGPA()))
{
list[i + 1] = list[i];
i--;
}
list[i + 1] = s;
}
void Course::display()
{
for (int i = 0; i < numStudents; i++)
{
cout<<list[i].getfirstName() <<" "<< list[i].getlastName() <<" "<< list[i].getstudentId() <<" "<< list[i].getphoneNumber() <<" "<< list[i].getGPA() << endl;
}
}
void Course::display(const string x, const int y)
{
if (y == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
}
void Course::remove(const string a, const int b)
{
if (b == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
}
void Course::sort_list()
{
string temp;
for (int i = 0; i < numStudents; i++)
{
for (int j = 0; j < numStudents-1; j++)
{
if(list[j].getfirstName() >list[j+1].getfirstName())
{
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
}
}
}
}
int main()
{
Student a("Kevin", "Chen", "300215915", "7788408028", 2);
Student b("Mickey", "Mouse", "12345678", "2222222222", 2.5);
Student c("Donald", "Duck", "24681012", "3333333333", 3.0);
Student d("Goofy", "Dog", "3579111315", "5555555555", 3.5);
Course x;
x.add(a);
x.add(b);
x.add(c);
x.add(d);
x.display();
cout << endl;
x.sort_list();
x.display();
/*cout << " " << endl;
x.remove("kevin", 1);
x.remove("Chen", 2);
x.remove("300215915", 3);
x.remove("7788408028", 4);
x.display();
cout << endl;
x.display("kevin", 1);
x.display("Mouse", 2);
x.display("24681012", 3);
x.display("5555555555", 4);*/
system("pause");
return 0;
}
It is true that your sorting code doesn't do anything.
Here is the core of it:
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
getfirstName() returns the first name by value so all your assignments are doing is swapping temporary copies of the first names. There is no effect on the actual list elements.
I think you meant:
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
This also means temp must be declared as a Student, not a std::string.
Also, unless I'm misremembering how Bubble Sort works (which is certainly possible — given its uselessness in the real world, it's been a long time since I've written one), your outer loop needs as many iterations as it takes for the inner loop not to be doing any swaps any more. If that's somehow inherently capped at numStudents iterations, I can't see why, nor see any evidence of it on the Wikipedia article.
Assuming I am on the right lines with that, I'd have the function looking like this:
void Course::sort_list()
{
bool go_again = false;
do {
go_again = false;
for (int i = 0; i < numStudents-1; i++) {
if (list[i].getfirstName() > list[i+1].getfirstName()) {
Student temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
go_again = true;
}
}
} while(go_again);
}
(live demo)

bad_alloc error in class definition

This is some code I'm working on for school. When I run it I get a bad_alloc error. It's most likely somewhere in the class definitions, but nothing i tried works. Can someone tell me where the bad allocation is happening?
#include <iostream>
#include <vector>
using namespace std;
enum Dir
{
LEFT = 1,
RIGHT = 1 << 1,
UP = 1 << 2,
DOWN = 1 << 3,
};
class Cell
{
friend class Board;
int row_, col_;
bool visited_;
unsigned int walls_;
Cell* up_;
Cell* down_;
Cell* left_;
Cell* right_;
Cell& set_up(Cell *up)
{
up_ = up;
return *this;
}
Cell& set_down(Cell *down)
{
down_ = down;
return *this;
}
Cell& set_left(Cell *left)
{
left_ = left;
return *this;
}
Cell& set_right(Cell *right)
{
right_ = right;
return *this;
}
public:
Cell( int row = -1, int col = -1)
:row_(row), col_(col), visited_(false), walls_(LEFT | RIGHT | UP | DOWN){}
bool visited() const
{
return visited_;
}
bool hasWall(Dir d) const
{
return walls_ & d;
}
void drill(Dir d)
{
walls_ &= ~d;
}
void draw(int step = 20) const
{
cout << col_*step << " " << row_*step << " " << "moveto" << endl;
cout << step << " " << 0 << " " << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << step << (hasWall(RIGHT)?"rlineto":"rmoveto") << endl;
cout << -step << " " << 0 << " " << (hasWall(UP)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << -step << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
}
Cell* up() const
{
return up_;
}
Cell* down() const
{
return down_;
}
Cell* left() const
{
return left_;
}
Cell* right() const
{
return right_;
}
};
class Board
{
friend class Cell;
int rows_, cols_;
vector<Cell> cells_;
public:
Board(int rows, int cols)
: rows_(rows), cols_(cols)
{
for(int i = 0; i < rows_; i++)
for (int j = 0; i < cols_; j++)
cells_.push_back(Cell(i, j));
for (int i = 0; i < rows_ ; i++)
for(int j = 0; j < cols_; j++)
{
Cell& c = at(i, j);
if(i < rows_ - 1)
c.set_up(&at(i + 1 , j));
if(i > 0)
c.set_down(&at(i - 1 , j));
if(j > 0)
c.set_left(&at(i , j - 1));
if(j < cols_ - 1)
c.set_right(&at(i, j + 1));
}
}
Cell& at(int i, int j)
{
int index = i*cols_ + j;
return cells_[index];
}
const Cell& at(int i, int j) const
{
int index = i*cols_ + j;
return cells_[index];
}
void draw() const
{
cout << "newpath" << endl;
for (vector<Cell>::const_iterator it = cells_.begin(); it != cells_.end(); ++it)
{
(*it).Cell::draw();
}
cout << "stroke" << endl;
cout << "showpage" << endl;
}
};
int main()
{
Board b(5, 5);
Cell& c = b.at(2, 2);
c.drill(UP);
Cell* up = c.up();
up->drill(DOWN);
b.draw();
return 0;
}
Board constructor - second for() you have wrong termination condition. There should be "j < cols_" instead of "i < cols_".

C++ Dynamic Arrays and Pointers in Polynomial program causes exit error 255

I'm currently doing a program that read in a degree, and coefficients and creates a polynomial struct. The program can add and multiply the polynomials, then output the sum or product. The program runs, outputs the correct answer, and then gets a windows error:
poly.exe has stopped working
A problem cause the program to stop working correctly. Windows will close the program and notify you if a solution is available.
then scite shows an exit code: 255
I think it could be something in the double for loop I am using for the multiply poly, or with the initialization of the pointer to the array of coefficients. But I cannot figure out what. The could I am using for it is as follows:
#include <iostream>
#include <stdio.h>
using namespace std;
struct Poly {
int degree;
int *coeff; //array of coefficients from lowest degree to highest degree
};
//Reads the coefficients of a polynomial from standard input
//Creates a poly struct and returns a pointer to the poly
Poly* readPoly();
//Outputs a polynomial to standard output with the variable x
void outputPoly(const Poly* p, char x);
//Computes the sum of two polynomials and returns
//a pointer to the new poly struct which is their sum
Poly* addPoly(const Poly* a, const Poly* b);
//Computes the product of two polynomials and returns
//a pointer to the new poly struct which is their product
Poly* multPoly(const Poly* a, const Poly* b);
//Returns to the heap the memory allocated for the polynomial
//and sets p to the nullptr
void deletePoly(Poly* &p);
Poly* readPoly() {
int deg;
//Read the highest degree
cout << "Input the degree: ";
cin >> deg;
//Handles when the degree is == 0
if(deg == 0) {
int *C = new int[deg+1];
Poly *p;
p = new Poly;
p->degree = deg;
p->coeff = C;
return p;
}
int *C = new int[deg+1];
//Read the coefficients
cout << "Input the coefficients: ";
for(int i = 0; i <= deg; i++) {
cin >> C[i];
}
//Create a new poly structure, assign its fields
//and retun a pointer to the new structure
Poly *p;
p = new Poly;
p->degree = deg;
p->coeff = C;
return p;
}
void outputPoly(const Poly* p, char x) {
//Set the degree and cooefficients to be used in the loop
int d = p->degree;
int *C = p->coeff;
//Output the polynomial, depending on the degree/coeff
for(int i = 0; i <= d; i++) {
//if the coeff is zero, and the degree is > 1
if(C[i] == 0 && i > 0)
continue; //Skip the +
//if the degree is 0, and the coeff is 0
else if(i == 0 && C[i] == 0) {
cout << C[i];
continue; //Skip the +
}
//if the degree is 0, and the coeff is not 0
else if(i == 0 && C[i] != 0)
cout << C[i];
//if the degree is 1, and the coeff is 0
else if(C[i] == 0 && i == 1)
cout << x;
//if the degree is 1, and the coeff is 1
else if(C[i] == 1 && i == 1)
cout << x;
//if the degree is 0, and the coeff is > 0
else if(C[i] > 0 && i == 0)
cout << C[i] << "*" << x;
//if the coefficient is 1
else if(C[i] == 1)
cout << x << "^" << i;
//if the degree is 1
else if(i == 1)
cout << C[i] << "*" << x;
//any other circumstance
else
cout << C[i] << "*" << x << "^" << i;
//Print a +, as long as it's not the last term
if(i != d)
cout << " + ";
}
}
void deletePoly(Poly* &p) {
delete[] p->coeff; //Delete the array first
delete p;
p = nullptr;
}
const Poly* getLargest(const Poly* a, const Poly* b) {
//Helper function to get the larger polynomial, given two
if(a->degree > b->degree)
return a;
else
return b;
}
const Poly* getSmallest(const Poly* a, const Poly* b) {
//Helper function to get the smaller polynomial, given two
if(a->degree < b->degree)
return a;
else
return b;
}
Poly* addPoly(const Poly* a, const Poly* b){
int i, j;
int *polyOneC = a->coeff;
int *polyTwoC = b->coeff;
//The new polynomials degree is the size of the polynomial that is the largest
int polyThreeD = getLargest(a, b)->degree;
int *polyThreeC = new int[polyThreeD];
for(i = 0, j = 0; j <= polyThreeD; i++, j++) {
//If the polynomials are of different size,
//then any coefficent term over the size
//of the smaller polynomial degree stays the same
if(i > getSmallest(a, b)->degree)
polyThreeC[i] = getLargest(a, b)->coeff[i];
else
//Otherwise, just add them
polyThreeC[i] = polyOneC[j] + polyTwoC[j];
//"Shifts" if it's equal to zero
if(polyThreeC[i] == 0)
i--;
}
//Ensures the remaining terms have a coefficient value(0)
while(i <= polyThreeD) {
polyThreeC[i] = 0;
i++;
}
Poly *sumPoly;
sumPoly = new Poly;
sumPoly->degree = polyThreeD;
sumPoly->coeff = polyThreeC;
return sumPoly;
}
Poly* multPoly(const Poly* a, const Poly* b) {
//Get the degrees and arrays of coefficients
int polyOneD = a->degree;
int polyTwoD = b->degree;
int *polyOneC = a-> coeff;
int *polyTwoC = b-> coeff;
int polyThreeD = polyOneD + polyTwoD;
int *polyThreeC = new int[polyThreeD + 1];
//Initialize the array of coefficients
for(int i = 0; i <= polyThreeD; i++)
polyThreeC[i] = 0;
//Multiple the coeffients and add to the position of the degree
for(int i = 0; i <= polyOneD; i++) {
for(int j = 0; j <= polyTwoD; j++) {
polyThreeC[i + j] += (polyOneC[i] * polyTwoC[j]);
}
}
//Create a new polynomial pointer and return it
Poly *productPoly;
productPoly = new Poly;
productPoly->degree = polyThreeD;
productPoly->coeff = polyThreeC;
return productPoly;
}
int main() {
Poly *x = readPoly();
Poly *y = readPoly();
//Test the add poly function
cout << "(";
outputPoly(x, 'x');
cout << ")";
cout << " + ";
cout << "(";
outputPoly(y, 'x');
cout << ")";
cout << endl;
//Call addPoly
Poly *z = addPoly(x, y);
cout << "= ";
cout << "(";
outputPoly(z, 'x');
cout << ")";
cout << endl;
cout << endl;
//Test the multiply poly function
cout << "(";
outputPoly(x, 'x');
cout << ")";
cout << " * ";
cout << "(";
outputPoly(y, 'x');
cout << ")";
cout << endl;
//Call multPoly
z = multPoly(x, y);
cout << "= ";
cout << "(";
outputPoly(z, 'x');
cout << ")";
cout << endl;
//Delete the polynomials now that we are done with them
deletePoly(x);
deletePoly(y);
deletePoly(z);
}
one other thing is that the error doesn't occur everytime it's run, so far I've witnessed it when I enter a polynomial with a degree of say 4. As opposed to a polynomial with a degree of 2, it works fine.
Can anyone help me!
You allocated coefficient array in addPoly (polyThreeC) isn't big enough. You forgot to add one to the degree when allocating the array.