1 #ifndef VECTOR_HPP
2 #define VECTOR_HPP
3
4 #include <iostream>
5 #include <stdexcept> // 用于异常处理
6
7 using namespace std;
8
9 template <typename T>
10 class Vector { // 类名修改为 MyVector,避免与 std::vector 冲突
11 private:
12 T* data; // 动态数组的指针
13 size_t size; // 数组的大小
14
15 public:
16 // 构造函数
17 Vector(size_t n, const T& value = T()) {
18 if (n < 0) {
19 throw length_error("Vector construction: negative size");
20 }
21 size = n;
22 data = new T[size];
23 for (size_t i = 0; i < size; ++i) {
24 data[i] = value;
25 }
26 }
27
28 // 拷贝构造函数
29 Vector(const Vector& other) {
30 size = other.size;
31 data = new T[size];
32 for (size_t i = 0; i < size; ++i) {
33 data[i] = other.data[i];
34 }
35 }
36
37 // 析构函数
38 ~Vector() {
39 delete[] data;
40 }
41
42 // 返回大小
43 size_t get_size() const {
44 return size;
45 }
46
47 // 带边界检查的 at()
48 T& at(size_t index) {
49 if (index >= size) {
50 throw out_of_range("Vector: index out of range");
51 }
52 return data[index];
53 }
54
55 const T& at(size_t index) const {
56 if (index >= size) {
57 throw out_of_range("Vector: index out of range");
58 }
59 return data[index];
60 }
61
62 // 重载输出流操作符
63 friend ostream& operator<<(ostream& os, const Vector<T>& v) {
64 for (size_t i = 0; i < v.size; ++i) {
65 os << v.data[i] << " ";
66 }
67 return os;
68 }
69 };
70
71 // 输出函数:简化输出向量内容
72 template <typename T>
73 void output(const Vector<T>& v) {
74 cout << v << endl;
75 }
76
77 #endif
78
79
80
81
82 #include <iostream>
83 #include "Vector.hpp"
84
85 void test1() {
86 using namespace std;
87
88 int n;
89 cout << "Enter n: ";
90 cin >> n;
91
92 Vector<double> x1(n);
93 for(auto i = 0; i < n; ++i)
94 x1.at(i) = i * 0.7;
95
96 cout << "x1: "; output(x1);
97
98 Vector<int> x2(n, 42);
99 const Vector<int> x3(x2);
100
101 cout << "x2: "; output(x2);
102 cout << "x3: "; output(x3);
103
104 x2.at(0) = 77;
105 x2.at(1) = 777;
106 cout << "x2: "; output(x2);
107 cout << "x3: "; output(x3);
108 }
109
110 void test2() {
111 using namespace std;
112
113 int n, index;
114 while(cout << "Enter n and index: ", cin >> n >> index) {
115 try {
116 Vector<int> v(n, n);
117 v.at(index) = -999;
118 cout << "v: "; output(v);
119 }
120 catch (const exception &e) {
121 cout << e.what() << endl;
122 }
123 }
124 }
125
126 int main() {
127 cout << "测试1: 模板类接口测试\n";
128 test1();
129
130 cout << "\n测试2: 模板类异常处理测试\n";
131 test2();
132 }