稀疏多项式求和用头文件源文件编写
时间: 2023-09-09 14:11:22 浏览: 96
好的,下面是稀疏多项式求和的头文件和源文件:
头文件(SparsePoly.h):
```c++
#ifndef SPARSEPOLY_H
#define SPARSEPOLY_H
#include <iostream>
#include <vector>
struct Term {
int coef; // 系数
int exp; // 次数
};
class SparsePoly {
private:
std::vector<Term> poly;
public:
SparsePoly() {} // 默认构造函数
SparsePoly(const std::vector<Term>& p); // 带参数构造函数
SparsePoly(const SparsePoly& p); // 复制构造函数
SparsePoly& operator=(const SparsePoly& p); // 赋值运算符重载
SparsePoly operator+(const SparsePoly& p) const; // 加法运算符重载
friend std::ostream& operator<<(std::ostream& os, const SparsePoly& p); // 输出运算符重载
};
#endif
```
源文件(SparsePoly.cpp):
```c++
#include "SparsePoly.h"
SparsePoly::SparsePoly(const std::vector<Term>& p) {
poly = p;
}
SparsePoly::SparsePoly(const SparsePoly& p) {
poly = p.poly;
}
SparsePoly& SparsePoly::operator=(const SparsePoly& p) {
if (this == &p) { // 自我赋值
return *this;
}
poly = p.poly;
return *this;
}
SparsePoly SparsePoly::operator+(const SparsePoly& p) const {
SparsePoly res;
int i = 0, j = 0;
while (i < poly.size() && j < p.poly.size()) {
if (poly[i].exp > p.poly[j].exp) {
res.poly.push_back(poly[i]);
i++;
} else if (poly[i].exp < p.poly[j].exp) {
res.poly.push_back(p.poly[j]);
j++;
} else {
int coef_sum = poly[i].coef + p.poly[j].coef;
if (coef_sum != 0) {
Term t;
t.coef = coef_sum;
t.exp = poly[i].exp;
res.poly.push_back(t);
}
i++;
j++;
}
}
while (i < poly.size()) {
res.poly.push_back(poly[i]);
i++;
}
while (j < p.poly.size()) {
res.poly.push_back(p.poly[j]);
j++;
}
return res;
}
std::ostream& operator<<(std::ostream& os, const SparsePoly& p) {
if (p.poly.empty()) {
os << "0";
return os;
}
for (int i = 0; i < p.poly.size(); i++) {
if (p.poly[i].coef > 0 && i > 0) {
os << "+";
}
os << p.poly[i].coef;
if (p.poly[i].exp > 1) {
os << "x^" << p.poly[i].exp;
} else if (p.poly[i].exp == 1) {
os << "x";
}
}
return os;
}
```
使用该头文件和源文件的方法如下:
```c++
#include <iostream>
#include "SparsePoly.h"
int main() {
std::vector<Term> p1 = {{1, 3}, {2, 1}, {-3, 0}}; // 1x^3 + 2x - 3
std::vector<Term> p2 = {{-1, 4}, {4, 2}, {2, 1}}; // -1x^4 + 4x^2 + 2x
SparsePoly poly1(p1);
SparsePoly poly2(p2);
std::cout << "poly1 = " << poly1 << std::endl;
std::cout << "poly2 = " << poly2 << std::endl;
SparsePoly poly3 = poly1 + poly2;
std::cout << "poly1 + poly2 = " << poly3 << std::endl;
return 0;
}
```
阅读全文