实验6 模板类、文件IO和异常处理

发布时间 2023-12-17 09:01:29作者: 春满城

实验任务4

 1 #define VECTOR_HPP
 2 #include <iostream>
 3 #include <stdexcept>
 4 using namespace std;
 5 template <typename T>
 6 class Vector {
 7 private:
 8     T* data; 
 9     size_t size; 
10 public:
11     Vector(size_t a) : size(a) {
12         data = new T[size];
13     }
14     Vector(size_t a, const T& value) : size(a) {
15         data = new T[size];
16         for (size_t i = 0; i < size; ++i) {
17             data[i] = value;
18         }
19     }
20     Vector(const Vector& other) : size(other.size) {
21         data = new T[size];
22         for (size_t i = 0; i < size; ++i) {
23             data[i] = other.data[i];
24         }
25     }
26     ~Vector() {
27         delete[] data;
28     }
29     size_t get_size() const {
30         return size;
31     }
32     T& at(size_t index) {
33         if (index < size) {
34             return data[index];
35         } else {
36             throw out_of_range("Index out of range");
37         }
38     }
39     T& operator[](size_t index) {
40         if (index < size) {
41             return data[index];
42         } else {
43             throw out_of_range("Index out of range");
44         }
45     }
46     friend void output(const Vector& vec) {
47         for (size_t i = 0; i < vec.size; ++i) {
48             cout << vec.data[i] << ',';
49         }
50         cout << endl;
51     }
52 };
Vector.hpp
 1 #include <iostream>
 2 #include "Vector.hpp"
 3 void test() {
 4     using namespace std;
 5     int n;
 6     cin >> n;
 7     Vector<double> x1(n);
 8     for(auto i = 0; i < n; ++i)
 9         x1.at(i) = i * 0.7;
10     output(x1);
11     Vector<int> x2(n, 42);
12     Vector<int> x3(x2);
13     output(x2);
14     output(x3);
15     x2.at(0) = 77;
16     output(x2);
17     x3[0] = 999;
18     output(x3);
19 }
20 int main() {
21     test();
22 }
task4.cpp

实验任务5

 1 #include<iostream>
 2 #include<iomanip>
 3 #include<fstream>
 4 
 5 using namespace std;
 6 
 7 void output(ostream &out) {
 8     for(int i=0;i<=26;i++){
 9         for(int j=0;j<=26;j++)
10         {
11             char m,n;
12             if(i==0&&j==0){
13                 char t = ' ';
14                 out<<setw(2)<<t;
15             }
16             else if(j==0&&i!=0){
17                 out<<setw(2)<<i;
18             }
19             else if(i==0&&j!=0){
20                 char m='a'+j-1;
21                 out<<setw(2)<<m;
22             }
23             else if(i!=0&&j!=0){
24                 char n=(i+j-1+26)%26+'A';
25                 out<<setw(2)<<n;
26             }
27 
28         }
29         out<<endl;
30     }
31 }
32 int main(){
33 
34     output(cout);
35 
36     ofstream outFile("cipher_key.txt");
37     output(outFile);
38     outFile.close();
39 
40     return 0;
41 }
task5.cpp