// P-3 MCS 360 due Mon 25 Oct 2010 : poly.tc #include #include "poly.h" #include template Poly::Poly(T c, int d) { Monomial m; m.coeff = c; m.deg = d; p.push_back(m); } template std::string Poly::to_string() { std::ostringstream s; if(p.empty()) s << "0"; else { typename std::list::iterator i; bool first = true; i = p.begin(); while(i != p.end()) { Monomial m = *i++; if(first) first = false; else if(m.coeff > 0) s << "+"; s << m.coeff << "*" << "x^" << m.deg; } } return s.str(); } template void Poly::add_monomial(const Monomial m) { typename std::list::iterator i; bool done = false; i = p.begin(); while(i != p.end()) { Monomial a = *i; if(a.deg == m.deg) { i->coeff = a.coeff + m.coeff; if(i->coeff == 0) i = p.erase(i); done = true; } if(done) break; i++; } if(!done) this->p.push_back(m); } template Poly Poly::operator+(const Poly& other) { Poly r = *this; std::list L = other.p; while(!L.empty()) { Monomial m = L.front(); r.add_monomial(m); L.pop_front(); } return r; }