标签:operations c polynomial-math
我正在尝试使用运算符重载来定义我的多项式类的基本操作(, – ,*,/)但是当我运行程序时它会崩溃并且我的计算机冻结.
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。