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
|
#include <iostream>
#include <stdexcept>
#include <memory>
struct polynomial
{
static constexpr std::size_t capacity = 1000 ; // max 1000 terms
// invariant: nterms <= capacity, if nterms > 0, then coeffs != nullptr and exps != nullptr
polynomial( std::size_t nterms, const double coeffs[], const int exps[] ) : nterms(nterms) // note: const
{
if( nterms > capacity ) throw std::out_of_range( "capacity exceeded" ) ;
if( nterms > 0 )
{
// http://en.cppreference.com/w/cpp/memory/uninitialized_copy
std::uninitialized_copy( coeffs, coeffs+nterms, coefficients ) ;
std::uninitialized_copy( exps, exps+nterms, exponents ) ;
}
}
std::size_t size() const { return nterms ; }
// addition etc.
// ...
private:
std::size_t nterms ;
double coefficients[capacity] = {} ; // initialise to all zeroes
int exponents[capacity] = {} ; // initialise to all zeroes
friend std::ostream& operator<< ( std::ostream& stm, const polynomial& poly )
{
for( std::size_t i = 0 ; i < poly.size() ; ++i )
stm << '(' << poly.coefficients[i] << ',' << poly.exponents[i] << ") " ;
return stm ;
}
};
int main()
{
const std::size_t n = 4 ;
const double coefficients[4] = { 1.5, -2.3, -4.8, 6.7 } ;
const int exponents[4] = { -2, 0, 3, 8 } ;
std::cout << polynomial( n, coefficients, exponents ) << '\n' ;
}
|