酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

(1). 编写冒泡排序的函数模板,要求对模板类型t的数组进行冒泡降序排序。 定义 txtdata类,要求在构造时打开文件(文件名由构造函数输入),并读取最多10个字符串,存入私有成员变量 strirns data[10]中。文件中按行存储字符串,一行一个。并在析构时向同一文件中按原文件的逆序写入字符串,每行一个,覆盖原有内容。 提示①:由于析构中需要向同一个文件写入,因此可在类中保存文件名。建议使用string 保存。 提示(2:读取后,注意判断流状态,什么样的流状态才表示读到了数据? 提示3:处理有效数据量不确定的数组,可参照顺序表的处理方法 (3) 定义 bindata 类,构造时如提供了文件名,则在构造函数中打开文件并按二进制方式读取最多10个整数存入私有成员变量 int data[201中。文件的格式是:整数按二进制方式保存在文件中,每个整数占用4字节。bindata 类不必保存文件名。析构时不保存数据。增加成员函数void savedata(const string s),功能是按下标顺序,将数据以二进制方式保存到s指定的文件中。为输出方便,可以重载插入符。 提示①:二进制文

(1). ```cpp #include <iostream> #include <fstream> #include <string> using namespace std; template <typename T> void bubbleSort(T arr[], int size) { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i - 1; j++) { if (arr[j] < arr[j+1]) { swap(arr[j], arr[j+1]); } } } } class txtdata { private: string filename; string data[10]; int count; public: txtdata(const string& filename) : filename(filename), count(0) { ifstream file(filename); if (file.is_open()) { string line; while (getline(file, line)) { data[count++] = line; if (count == 10) { break; } } } file.close(); } ~txtdata() { ofstream file(filename, ios::out | ios::trunc); if (file.is_open()) { for (int i = count - 1; i >= 0; i--) { file << data[i] << endl; } } file.close(); } }; int main() { int arr[] = { 5, 3, 8, 1, 2 }; int size = sizeof(arr) / sizeof(arr[0]); bubbleSort<int>(arr, size); for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; return 0; } ``` (3). ```cpp #include <iostream> #include <fstream> #include <string> using namespace std; class bindata { private: int data[10]; public: bindata(const string& filename = "") { if (!filename.empty()) { ifstream file(filename, ios::binary); if (file.is_open()) { file.read(reinterpret_cast<char*>(data), sizeof(data)); } file.close(); } } void savedata(const string& filename) { ofstream file(filename, ios::binary); if (file.is_open()) { file.write(reinterpret_cast<char*>(data), sizeof(data)); } file.close(); } friend ostream& operator<<(ostream& os, const bindata& bd) { for (int i = 0; i < sizeof(bd.data) / sizeof(bd.data[0]); i++) { os << bd.data[i] << " "; } return os; } }; int main() { bindata bd("data.bin"); cout << bd << endl; bd.savedata("output.bin"); return 0; } ``` [2024-06-01 16:02:33 | AI写代码神器 | 1551点数解答]

相关提问