C++编程:冒泡排序函数模板、txtdata类与bindata类的实现及应用
(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; } ``` ######[AI写代码神器 | 1551点数解答 | 2024-06-01 16:02:33]
- C++:bindata 类实现文件二进制整数读取、排序与归并合并输出(GPT | 1814点数解答 | 2024-06-01 16:28:14)312
- C++:bindata 类实现文件二进制读取、排序与归并合并输出(GPT | 811点数解答 | 2024-06-01 16:29:51)293
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)343
- C++:冒泡排序函数模板与文件读写类(txtdata、bindata)的实现及应用(GPT | 1941点数解答 | 2024-06-01 16:23:06)310
- C 语言实现链表操作:创建、输出、删除及插入功能详解(字节豆包 | 534点数解答 | 2024-12-09 21:33:48)338
- C语言实现链表创建、输出、删除与插入操作的完整代码及注意要点(字节豆包 | 609点数解答 | 2024-12-18 12:18:21)358
- C++编程:冒泡排序函数模板、txtdata类与bindata类的实现及应用(GPT | 1551点数解答 | 2024-06-01 16:02:33)325
- 不使用冒泡排序,用归并排序降序合并 bina 与 binb 并输出结果!(GPT | 48点数解答 | 2024-06-01 16:26:38)318
- Express 应用创建与数据查询 API 实现:附代码示例与注意要点(字节豆包 | 387点数解答 | 2024-12-05 09:09:59)224
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)310
- Spring项目:实现UserMapper接口及XML映射文件,查询所有用户信息(GPT | 445点数解答 | 2024-09-12 14:40:40)198
- 解决 consoleapplication40.cpp 中 buildtree 模板参数推导失败错误的方法(字节豆包 | 138点数解答 | 2024-11-10 23:42:06)238