C++
时间: 2023-07-11 09:23:23 浏览: 84
A tour of C++
好的,以下是C++的代码实现:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// 多项式结构体
struct Polynomial {
vector<int> coefficient; // 系数数组,从低次到高次排序
};
// 读取文件中的多项式
vector<Polynomial> readPolynomialsFromFile(const string& filename) {
vector<Polynomial> polynomials;
ifstream file(filename);
if (file.is_open()) {
string line;
while (getline(file, line)) {
Polynomial p;
int coefficient;
istringstream iss(line);
while (iss >> coefficient) {
p.coefficient.push_back(coefficient);
}
polynomials.push_back(p);
}
file.close();
}
return polynomials;
}
// 比较多项式的次数,用于排序
bool comparePolynomialDegree(const Polynomial& p1, const Polynomial& p2) {
return p1.coefficient.size() < p2.coefficient.size();
}
// 将多项式按照次数升序排列并输出
void sortAndPrintPolynomials(const vector<Polynomial>& polynomials) {
vector<Polynomial> sortedPolynomials = polynomials;
sort(sortedPolynomials.begin(), sortedPolynomials.end(), comparePolynomialDegree);
for (const auto& p : sortedPolynomials) {
for (int i = 0; i < p.coefficient.size(); i++) {
cout << p.coefficient[i] << "x^" << i << " + ";
}
cout << "0" << endl;
}
}
// 将多项式按照次数升序排列并输出到文件
void sortAndWritePolynomialsToFile(const vector<Polynomial>& polynomials, const string& filename) {
vector<Polynomial> sortedPolynomials = polynomials;
sort(sortedPolynomials.begin(), sortedPolynomials.end(), comparePolynomialDegree);
ofstream file(filename);
if (file.is_open()) {
for (const auto& p : sortedPolynomials) {
for (int i = 0; i < p.coefficient.size(); i++) {
file << p.coefficient[i] << "x^" << i << " + ";
}
file << "0" << endl;
}
file.close();
}
}
int main() {
string filename = "polynomials.txt";
vector<Polynomial> polynomials = readPolynomialsFromFile(filename);
sortAndPrintPolynomials(polynomials);
sortAndWritePolynomialsToFile(polynomials, "sorted_polynomials.txt");
return 0;
}
```
这里假设文件中每个多项式单独一行,每个多项式的项数和系数用空格隔开。程序首先读取文件中的多项式,然后按照次数升序排列并输出到屏幕和文件。在输出时,程序按照 $ax^b + cx^d + ...$ 的格式输出每个多项式。
阅读全文