1 #include <iostream>
2 #include <stdexcept>
3 #include <ostream>
4
5 template <typename T>
6 class Vector {
7 public:
8 Vector() : data(nullptr), size(0) {}
9
10 explicit Vector(int size) : data(new T[size]), size(size) {}
11
12 Vector(int size, const T& value) : data(new T[size]), size(size) {
13 for (int i = 0; i < size; ++i) {
14 data[i] = value;
15 }
16 }
17
18 Vector(const Vector<T>& other) : data(new T[other.size]), size(other.size) {
19 for (int i = 0; i < size; ++i) {
20 data[i] = other.data[i];
21 }
22 }
23
24 ~Vector() {
25 delete[] data;
26 }
27
28 int get_size() const {
29 return size;
30 }
31
32 T& at(int index) {
33 if (index < 0 || index >= size) {
34 throw std::out_of_range("索引越界");
35 }
36 return data[index];
37 }
38
39 T& operator[](int index) {
40 return at(index);
41 }
42
43 friend void output(const Vector<T>& v) {
44 for (int i = 0; i < v.size; ++i) {
45 std::cout << v.data[i] << " ";
46 }
47 std::cout << std::endl;
48 }
49
50 private:
51 T* data;
52 int size;
53 };
54
55 void test() {
56 using namespace std;
57 int n;
58 cin >> n;
59
60 Vector<double> x1(n);
61 for (auto i = 0; i < n; ++i)
62 x1.at(i) = i * 0.7;
63 output(x1);
64
65 Vector<int> x2(n, 42);
66 Vector<int> x3(x2);
67 output(x2);
68 output(x3);
69
70 x2.at(0) = 77;
71 output(x2);
72 x3[0] = 999;
73 output(x3);
74
75 cout << "x3.get_size() = " << x3.get_size() << endl;
76 }
77
78 int main() {
79 test();
80 return 0;
81 }