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

编写冒泡排序的函数模板,要求对模板类型t的数组进行冒泡降序排序。定义 txtdata类,要求在构造时打开文件(文件名由构造函数输入),并读取最多10个字符串,存入私有成员变量 strirns data[10]中。文件中按行存储字符串,一行一个。并在析构时向同一文件中按原文件的逆序写入字符串,每行一个,覆盖原有内容 定义 bindata 类,构造时如提供了文件名,则在构造函数中打开文件并按二进制方式读取最多10个整数存入私有成员变量 int data[201中。文件的格式是:整数按二进制方式保存在文件中,每个整数占用4字节。bindata 类不必保存文件名。析构时不保存数据。增加成员函数void savedata(const string s),功能是按下标顺序,将数据以二进制方式保存到s指定的文件中。为输出方便,可以重载插入符。二进制文件的读写,分别用成员函数read, write, 不能使用提取符或插入符读取后,注意判断流状态。 用 txtdata txt("c:isy1311123.txt)定义对象;随后在屏幕上输出该文件中的字符串。 用bindata bina("c:lisy13

以下是冒泡排序的函数模板的代码: ```cpp 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]) { std::swap(arr[j], arr[j + 1]); } } } } ``` 以下是 txtdata 类的代码: ```cpp #include <iostream> #include <fstream> #include <string> #include <algorithm> class txtdata { private: std::string stringsData[10]; public: txtdata(const std::string& filename) { std::ifstream file(filename); if (!file) { std::cout << "Failed to open the file." << std::endl; return; } std::string line; int count = 0; while (count < 10 && std::getline(file, line)) { stringsData[count++] = line; } file.close(); } ~txtdata() { std::ofstream file("reversed.txt"); if (!file) { std::cout << "Failed to open the file." << std::endl; return; } std::reverse(stringsData, stringsData + 10); for (int i = 0; i < 10; i++) { file << stringsData[i] << std::endl; } file.close(); } }; ``` 以下是 bindata 类的代码: ```cpp #include <iostream> #include <fstream> #include <string> #include <algorithm> class bindata { private: int intData[10]; public: bindata(const std::string& filename = "") { if (filename != "") { std::ifstream file(filename, std::ios::binary); if (!file) { std::cout << "Failed to open the file." << std::endl; return; } file.read(reinterpret_cast<char*>(intData), 10 * sizeof(int)); if (!file) { std::cout << "Failed to read the file." << std::endl; return; } file.close(); } } ~bindata() {} void savedata(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) { std::cout << "Failed to open the file." << std::endl; return; } file.write(reinterpret_cast<const char*>(intData), 10 * sizeof(int)); if (!file) { std::cout << "Failed to write the file." << std::endl; return; } file.close(); } friend std::ostream& operator<<(std::ostream& os, const bindata& obj) { for (int i = 0; i < 10; i++) { os << obj.intData[i] << std::endl; } return os; } }; ``` 以下是使用示例代码: ```cpp int main() { txtdata txt("c:\\isy1311123.txt"); for (int i = 0; i < 10; i++) { std::cout << txt.stringsData[i] << std::endl; } bindata bina("c:\\lisy13.bin"); std::cout << bina; return 0; } ``` [2024-06-01 16:23:06 | AI写代码神器 | 1941点数解答]

相关提问