用STL中的list模板类实现的简单多项式类

#ifndef _polynomial_h #define _polynomial_h #include <list> struct Term { int exponent; int coef; }; typedef std::list<Term> TermList; class Polynomial { TermList terms; public: Polynomial(void); ~Polynomial(void); public: void operator + (Polynomial * p); //Polynomial & operator - (const Polynomial * p); //Polynomial & operator * (const Polynomial * p); void Clear(); bool IsEmpty() const; int TermCount() const; void Print() const; private: void Create(); }; #endif //------------------------------------------------ #include "Polynomial.h" #include <iostream> #include <list> using namespace std; Polynomial::Polynomial(void) { Create(); } Polynomial::~Polynomial(void) { terms.clear(); } void Polynomial::operator +(Polynomial * p) { //std::list<Term>::iterator Iter; list<Term>::iterator iter0 = this->terms.begin(); list<Term>::iterator iter1 = p->terms.begin(); while(iter0 != terms.end() && iter1 != p->terms.end()) { if(iter0->exponent == iter1->exponent) { int sumCoef = iter0->coef + iter1->coef; if(sumCoef != 0) { iter0->coef = sumCoef; } else { iter0 = terms.erase(iter0); } iter0++; iter1++; } else if(iter0->exponent < iter1->exponent) { iter0++; } else { terms.insert(iter0, * iter1); iter1++; } } while(iter1 != p->terms.end()) { terms.push_back(* iter1++); } } void Polynomial::Print() const { typedef std::list<Term>::const_iterator Iter; for(Iter iter = terms.begin(); iter != terms.end(); iter++) { cout<< iter->coef <<" * x^"<<iter->exponent<<" + "; } cout<<endl; } int Polynomial::TermCount() const { return terms.size(); } bool Polynomial::IsEmpty() const { return terms.size() == 0; } void Polynomial::Clear() { terms.clear(); } void Polynomial::Create() { Term term; term.coef = 1; term.exponent = 2; terms.push_back(term); term.coef = 2; term.exponent = 3; terms.push_back(term); term.coef = 3; term.exponent = 4; terms.push_back(term); }

你可能感兴趣的:(list,iterator)