其他分享
首页 > 其他分享> > c – 使用运算符重载的多项式运算

c – 使用运算符重载的多项式运算

作者:互联网

我正在尝试使用运算符重载来定义我的多项式类的基本操作(, – ,*,/)但是当我运行程序时它会崩溃并且我的计算机冻结.

UPDATE4

好.我成功完成了三次操作,剩下的唯一一次是划分.

这是我得到的:

polinom operator*(const polinom& P) const
{
    polinom Result;
    constIter i, j, lastItem = Result.poly.end();
    Iter it1, it2, first, last;
    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);
    }

    Result.poly.sort(SortDescending());

    lastItem--;

    while (true) {
        nr_matches = 0;

        for (it1 = Result.poly.begin(); it1 != lastItem; it1++) {
             first = it1;
             last = it1;
             first++;
             for (it2 = first; it2 != Result.poly.end(); it2++) { 
                  if (it2->pow == it1->pow) {
                      it1->coef += it2->coef;
                      nr_matches++;
                  }
             }

             nr_matches++;
             do {
                last++;
                nr_matches--;
             } while (nr_matches != 0);

             Result.poly.erase(first, last);
        }   
        if (nr_matches == 0)
            break;
    }     

    return Result;
}

解决方法:

至于正确添加多项式函数,我推荐这个简单的逻辑:

polinom operator+(const polinom& P) const //fixed prototype re. const-correctness
{
    polinom Result;
    std::list<term>::const_iterator //fixed iterator type
        i = poly.begin(), j = P.poly.begin();

    while (i != poly.end() && j != P.poly.end()) {
        //logic while both iterators are valid
    }

    //handle the remaining items in each list
    //note: at least one will be equal to end(), but that loop will simply be skipped

    while (i != poly.end()) {
        Result.insert(i->coef, i->pow);
        ++i;
    }

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

    return Result;
}

最后一部分也可能留给标准库函数

#include <iterator>
#include <algorithm>

//...
    //handle remaining items in either list (if any)
     std::copy(i, poly.end(), std::back_inserter(Result.poly));
     std::copy(j, P.poly.end(), std::back_inserter(Result.poly));

…但使用list.insert可能会更简单:

     Result.poly.insert(Result.poly.end(), i, poly.end());
     Result.poly.insert(Result.poly.end(), j, P.poly.end());

标签:operations,c,polynomial-math
来源: https://codeday.me/bug/20190726/1546633.html