酷代码 AI
菜单
服务商

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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]