Polynomial operations using operator overloading

Posted by Vlad on Stack Overflow See other posts from Stack Overflow or by Vlad
Published on 2010-03-11T14:00:04Z Indexed on 2010/03/12 12:47 UTC
Read the original article Hit count: 543

Filed under:
|
|

I'm trying to use operator overloading to define the basic operations (+,-,*,/) for my polynomial class but when i run the program it crashes and my computer frozes.

Update3

Ok i successfully done the first two operations(+,-). Now at multiplication, after multiplying each term of the first polynomial with each of the second i want to sort the poly list descending and then if there are more than one term with the same power to merge them in only one term, but for some reason it doesn't compile because of the sort function which doesn't work.

Here's what I got:

polinom operator*(const polinom& P) const
{
    polinom Result;
    constIter i, j, lastItem = Result.poly.end();
    Iter it1, it2;
    int nr_matches;

    for (i = poly.begin() ; i != poly.end(); i++) {
         for (j = P.poly.begin(); j != P.poly.end(); j++)
              Result.insert(i->coef * j->coef, i->pow + j->pow);
    }

    sort(Result.poly.begin(), Result.poly.end(), SortDescending());

    lastItem--;

    while (true) {
        nr_matches = 0;

        for (it1 = Result.poly.begin(); it < lastItem; it1++) {
             for (it2 = it1 + 1;; it2 <= lastItem; it2++){ 
                  if (it2->pow == it1->pow) {
                      it1->coef += it2->coef;
                      nr_matches++;
                  }
             }

             Result.poly.erase(it1 + 1, it1 + (nr_matches + 1));
        }       

    return Result;
}

Also here's SortDescending:

struct SortDescending
{
    bool operator()(const term& t1, const term& t2)
    { 
        return t2.pow < t1.pow; 
    }
};

What did i do wrong?

Thanks!

© Stack Overflow or respective owner

Related posts about c++

Related posts about polynomial-math