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
|
#include <iostream>
#include <map>
#include <iomanip>
//polynomials:
class Poly
{
private:
// key expnent, mapped value: coefficient
// std::greater<>: as we go through the list, the exponents decrease
std::map< unsigned int, double, std::greater<> > terms ;
public:
Poly( std::initializer_list< std::pair< double, unsigned int > > ilist = {} )
{ for( const auto& pair : ilist ) addTerm( pair.first, pair.second ) ; }
void addTerm( double coef, int exp ) { terms[exp] += coef ; }
Poly& operator+= ( const Poly& that )
{
for( const auto& pair : that.terms ) addTerm( pair.second, pair.first ) ;
return *this ;
}
friend Poly operator+ ( Poly a, const Poly& b ) { return a += b ; }
friend std::ostream& operator<< ( std::ostream& stm, const Poly& p )
{
if( p.terms.empty() ) return stm << "0 " ;
static const auto print_term = [&stm]( auto iter )
{
stm << std::setw(7) << iter->second ;
if( iter->first == 1 ) stm << "x " ;
else if( iter->first > 1 ) stm << "x^" << iter->first << ' ' ;
};
// print the first term
auto iter = p.terms.begin() ;
stm << std::fixed << std::setprecision(2) << std::noshowpos << std::right ;
print_term(iter) ;
// print the remaining terms
stm << std::showpos << std::internal ;
for( ++iter ; iter != p.terms.end() ; ++iter ) print_term(iter) ;
return stm ;
}
};
int main()
{
Poly a( { {3.0,5}, {2.1,2}, {1.6,5}, {7.0,0}, {-22.0,1}, {3.6,2} } );
Poly b( { {-2.8,5}, {9.3,4}, {-17.2,0}, {-1.6,7} } );
std::cout << "a: " << a << '\n'
<< "b: " << b << '\n'
<< "a+b: " << a+b << '\n' ;
}
|