1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class term{
private:
double coeff;
int power;
public:
void setCoeff(double x) {coeff = x;}
void setPower(int x) {power = x;}
double getCoeff() const {return coeff;}
double getPower() const {return power;}
term(double a, int b) {coeff = a, power = b;};
term() = default;
};
struct lessThanTerm{
inline bool operator() (const term& nr1, const term& nr2){
return (nr1.getCoeff() > nr2.getCoeff());
}
};
class polynomial{
private:
vector<term> termm;
public:
term getTerm(unsigned n) { return termm[n];}
int polySize() { return termm.size();}
void sortPoly() { sort(termm.rbegin(), termm.rend(),
lessThanTerm());}
/*void sortPoly() { sort(termm.rbegin(), termm.rend(),
[this](termm){ return };}*/
void append(term h) { termm.push_back(h);}
polynomial(term h) { termm.push_back(h);};
polynomial() = default;
//void simplify
};
ostream& operator<<(ostream& o, term z){
if(z.getPower() > 1)
o << z.getCoeff() << "x^" << z.getPower();
else if(z.getPower() == 1)
o << z.getCoeff() << "x";
else if(z.getPower() == 0)
o << z.getCoeff();
return o;
}
ostream& operator<<(ostream& o, polynomial z){
//z.sortPoly();
for(int v = 0; v <= z.polySize()-1; v+=1){
o << z.getTerm(v);
if(v < z.polySize()-1)
cout << "+";
}
return o;
}
istream& operator>>(istream& in, polynomial g){
string z;
cout << "Enter a polynomial in the form \"ax^n+....+bx^0\": ";
in >> z;
double coeff = 0;
int power = 0;
string coef;
string pwr;
int lengthOne = z.length();
int lengthTwo = 0;
for(auto i : z){
coef.push_back(i);
pwr.push_back(i);
lengthTwo+=1;
if(i == 'x'){
coeff = stoi(coef);
continue;
}
else if(i == '^'){
pwr.clear();
continue;
}
else if(i == '+'){
power = stoi(pwr);
term temp{coeff, power};
g.append(temp);
cout << temp << '\n';
coeff = 0;
power = 0;
coef.clear();
continue;
}
else if(lengthOne == lengthTwo){
//cout << lengthOne << '\t' << lengthTwo << '\n';
term temp2{coeff, 0};
g.append(temp2);
cout << temp2 << '\n';
}
/*cout << coeff << '\t' << power << '\n';
cout << coef << '\t' << pwr << '\n';*/
}
return in;
}
int main()
{
polynomial b;
cin >> b;
cout << b.polySize() << '\n';
cout << b << '\n';
return EXIT_SUCCESS;
}
|