模板类与文件I/O应用实例
在本示例中,我们将展示如何使用模板类、文件输入输出以及异常处理。首先定义一个动态数组类,并实现基本的操作和异常处理机制。
#pragma once
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class DynamicArray {
private:
int arraySize;
T* elements;
template<typename U>
friend void display(const DynamicArray<U>& arr);
public:
DynamicArray(int size) {
if (size < 0) throw length_error("Negative size not allowed");
elements = new T[size];
arraySize = size;
}
DynamicArray(int size, const T& value) {
if (size < 0) throw length_error("Negative size not allowed");
elements = new T[size];
arraySize = size;
for (int i = 0; i < size; ++i) elements[i] = value;
}
~DynamicArray() {
delete[] elements;
}
int getSize() const { return arraySize; }
T& getElement(int index) const {
if (index < 0 || index >= arraySize) throw out_of_range("Index out of bounds");
return elements[index];
}
T& operator[](int index) {
if (index >= arraySize) throw out_of_range("Index out of bounds");
return elements[index];
}
};
template<typename U>
void display(const DynamicArray<U>& arr) {
for (int i = 0; i < arr.getSize(); ++i) {
cout << arr.getElement(i) << ", ";
}
cout << "\b\b " << endl;
}
接下来,我们通过几个测试函数来验证上述类的功能。
#include <iostream>
#include "DynamicArray.hpp"
using namespace std;
void testCase1() {
int n;
cout << "请输入数组大小n: ";
cin >> n;
DynamicArray<double> arr1(n);
for (int i = 0; i < n; ++i) arr1.getElement(i) = i * 0.5;
cout << "arr1: "; display(arr1);
DynamicArray<int> arr2(n, 33);
const DynamicArray<int> arr3(arr2);
cout << "arr2: "; display(arr2);
cout << "arr3: "; display(arr3);
arr2[0] = 99;
arr2[1] = 999;
cout << "更新后的arr2: "; display(arr2);
cout << "未变的arr3: "; display(arr3);
}
void testCase2() {
int n, idx;
while (cout << "请输入数组大小n和索引idx: ", cin >> n >> idx) {
try {
DynamicArray<int> vec(n, n);
vec.getElement(idx) = -888;
cout << "vec: "; display(vec);
} catch (const exception& e) {
cout << e.what() << endl;
}
}
}
int main() {
cout << "测试案例1: 模板类接口\n";
testCase1();
cout << "\n测试案例2: 异常处理\n";
testCase2();
}
最后,我们还将演示如何使用文件I/O进行数据的读取和写入操作。
#include "Student.hpp"
#include "utils.hpp"
#include <vector>
#include <algorithm>
int main() {
vector<Student> students;
load("studentData.txt", students);
sort(students.begin(), students.end(), compareByMajor);
output(cout, students);
save("sortedStudents.txt", students);
return 0;
}