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
|
#include <iostream>
#include <list>
struct term
{
// The Term class should store an integer degree and a double coefficient.
int degree ;
double coefficient ;
friend std::ostream& operator<< ( std::ostream& stm, const term& t ) // display a term
{ return stm << t.coefficient << " x^" << t.degree ; }
};
struct polynomial
{
polynomial() = default ; // Create a new empty polynomial
// Your class should have methods to add and remove terms to and from a polynomial.
// You should store the polynomial in descending order of degrees.
void add_term( const term& a_term )
{
// check if there already is a term with this degree
for( term& t : terms ) if( t.degree == a_term.degree )
{
t.coefficient += a_term.coefficient ; // if there is one, add the coefficient to it
return ; // and we are done
}
// we did not find a term with this degree, add this term to he back of the list
terms.push_back(a_term) ;
// and rearrange the list to store the polynomial in descending order of degrees.
// (note: this is certainly not the most efficient way, but it is adequate for our purposes
// we do not expect this polynomial to hold scores of terms).
terms.sort( []( const term& a, const term& b ) { return a.degree > b.degree ; } ) ;
}
friend std::ostream& operator<< ( std::ostream& stm, const polynomial& poly ) // display a polynomial
{
// std::showpos: place a + or - sign before each number
stm << std::showpos << "[ " ;
for( const term& t : poly.terms ) stm << t << " " ;
return stm << ']' ;
}
// The Polynomial class should store a linked list of terms
std::list<term> terms ;
};
int main()
{
polynomial poly ; // create an empty polynomial
// add some terms to it and print out the result
for( term t : { term{-1,2.3}, term{2,5.6}, term{3,6.7}, term{-1,-4.2}, term{2,-8.2} } )
{
std::cout << poly << " plus " << t << " == " ;
poly.add_term(t) ;
std::cout << poly << '\n' ;
}
}
|