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

发布于 2024-08-25 03:35:00 字数 1296 浏览 9 评论 0原文

我试图使用运算符重载来定义多项式类的基本运算(+、-、*、/),但是当我运行程序时,它崩溃了,我的计算机冻结了。

更新4

好的。我成功地进行了三个操作,只剩下一个是除法。

这是我得到的:

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;
}

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.

Update4

Ok. i successfully made three of the operations, the only one left is division.

Here's what I got:

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

∝单色的世界 2024-09-01 03:35:01

崩溃发生在这一行中。

 if (i->pow > P.i->pow) 

您的代码还存在其他设计和正确性问题,但我认为当 i == poly.end() && 时, Pi != P.End() 或 i != poly.end() && Pi == P.End()。当 i 指向最后一个元素之后时取消引用 i 将会崩溃。

There are other design and correctness issues with your code, but I think the crash occurs in this line

 if (i->pow > P.i->pow) 

when i == poly.end() && P.i != P.End() or i != poly.end() && P.i == P.End(). Dereferencing i when it points after the last element will crash.

九八野马 2024-09-01 03:35:01

至于让函数正确地累加多项式,我建议使用这个简单的逻辑:

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());

As to getting the function correctly adding up polynomials, I'd recommend this simple logic:

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;
}

The last part can probably also be left to standard library functions

#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));

... but would probably be simpler using list.insert:

     Result.poly.insert(Result.poly.end(), i, poly.end());
     Result.poly.insert(Result.poly.end(), j, P.poly.end());
老娘不死你永远是小三 2024-09-01 03:35:00
while (i != poly.end() || P.i != P.End())

我想你需要 &&否则,只有当 i 和 pi 同时到达各自的终点时,循环才会终止。

带有否定的逻辑是很棘手的。可能更简单地将其视为:

while (!(i == poly.end() || j == P.End())) //while neither iterator has reached end

根据布尔算术,它与以下内容相同:

while (!(i == poly.end()) && !(j == P.End()))
while (i != poly.end() && j != P.End())

如果两者相等,您似乎也不会增加迭代器(无限循环导致无限多个内存分配?)。


风格问题:最好使用迭代器作为局部变量。如果在方法中开始使用变量之前应该“初始化”变量,则不要将变量设置为类成员,并且在方法完成后它们将变得无用。

也更喜欢通过 const 引用传递参数,如果成员函数不修改当前对象(operator+ 不应该),则标记成员函数 const :(

 polinom operator+(const polinom& P) const;

这会揭示问题本地使用的迭代器成员 - 您将修改实例!)

while (i != poly.end() || P.i != P.End())

I think you'll need && there, otherwise the loop terminates only if i and p.i reach their respective end at the same time.

Logic with negations is tricky. Probably simpler to think of this as:

while (!(i == poly.end() || j == P.End())) //while neither iterator has reached end

which according to boolean arithmetic is the same as:

while (!(i == poly.end()) && !(j == P.End()))
while (i != poly.end() && j != P.End())

You also don't seem to be incrementing the iterators if both are equal (infinite loop leading to infinitely many memory allocations?).


Style issues: you are better off using iterators as local variables. Don't make variables class members if they are supposed to be "initialized" before you start using them in a method, and they become useless after the method completes.

Also prefer passing arguments by const reference, and mark member functions const if they don't modify the current object (operator+ shouldn't):

 polinom operator+(const polinom& P) const;

(which would reveal the problem making locally used iterators members - you would be modifying the instances!)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文