C++ STL 第七次实验

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39776901/article/details/78596587

【题目】
  压缩书上类Polynomial类中的AddPolynomial()方法,使其少于十行

#include <iostream>
#include <list>
#include <string>

using namespace std;

class Term
{
private:
    int coef;
    int exp;
public:
    Term(int coef,int exp):coef(coef),exp(exp){}
    int GetCoef(){return coef;}
    int GetExp(){return exp;}
    bool operator< (Term& t)
    {
        return exp<t.GetExp();
    }
    bool operator == (const Term& t){
        if (exp == t.exp)
        {
            coef += t.coef;
            return 1;
        }
            return 0;
    }
};

typedef list<Term> LISTTERM;

ostream& operator<< (ostream& os,Term& t)
{
    os << t.GetCoef() << "x" << t.GetExp();
    return os;
}

bool same_integral_part(Term &first, Term &second)
{
    return first == second;
}

class Polynomial
{
private:
    LISTTERM m_termList;
public:
    bool AddTerm(const Term& t)
    {
        m_termList.push_back(t);
        return true;
    }

    void AddPolynomial(Polynomial& obj)
    {
        obj.m_termList.splice(obj.m_termList.begin(),m_termList);
        obj.m_termList.sort();
        obj.m_termList.unique(same_integral_part);

        for (list<Term>::iterator it = obj.m_termList.begin(); it != obj.m_termList.end(); it++)
        {
                if ((*it).GetCoef() == 0)
                {
                    obj.m_termList.erase(it);   //移除系数为0的
                    break;
                }
        }
    }

    void Show()
    {
        LISTTERM::iterator it = m_termList.begin();
        while(it!=m_termList.end())
        {
            cout << *it << "+";
            it++;
        }
    }
};

int main()
{
    Polynomial p1;
    Polynomial p2;

    Term t1(2,6);
    Term t2(3,4);
    Term t3(5,2);
    Term t4(6,0);

    p1.AddTerm(t1);
    p1.AddTerm(t2);
    p1.AddTerm(t3);
    p1.AddTerm(t4);

    Term t5(2,5);
    Term t6(-3,4);
    Term t7(5,2);
    Term t8(8,0);

    p2.AddTerm(t5);
    p2.AddTerm(t6);
    p2.AddTerm(t7);
    p2.AddTerm(t8);

    p1.AddPolynomial(p2);
    p2.Show();
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39776901/article/details/78596587