【发布时间】:2010-03-11 14:00:04
【问题描述】:
我正在尝试使用运算符重载来为我的多项式类定义基本运算(+、-、*、/),但是当我运行程序时它崩溃并且我的计算机死机了。
更新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;
}
【问题讨论】:
-
编辑后问题变得完全不同。我不太明白,既然您永远不会让迭代器等于结尾,那么循环如何终止。
-
我明白它为什么会停止,这是因为它会插入 3x^2,直到它最终耗尽内存并导致我的计算机崩溃。现在来看看如何解决它。
-
你的“last”函数没有返回任何东西。这可能会导致问题。
-
是的,马克,谢谢!
标签: c++ operations polynomial-math