CHENSHAOQIU

导航

 
实验任务4
 1 #pragma once
 2 #include <iostream>
 3 #include <stdexcept>
 4 
 5 template <class T>
 6 class Vector {
 7 private:
 8     T* data;
 9     size_t size;
10 
11 public:
12     Vector() : data(nullptr), size(0) {}
13 
14     Vector(size_t initialSize, const T& value = T()) : size(initialSize) {
15         data = new T[size];
16         for (size_t i = 0; i < size; i++) {
17             data[i] = value;
18         }
19     }
20 
21     Vector(const Vector& other) : size(other.size) {
22         data = new T[size];
23         for (size_t i = 0; i < size; i++) {
24             data[i] = other.data[i];
25         }
26     }
27 
28     ~Vector() {
29         delete[] data;
30     }
31 
32     size_t get_size() const {
33         return size;
34     }
35 
36     T& at(size_t index) {
37         if (index >= size) {
38             throw std::out_of_range("Index out of range");
39         }
40         return data[index];
41     }
42 
43     T& operator[](size_t index) {
44         if (index >= size) {
45             throw std::out_of_range("Index out of range");
46         }
47         return data[index];
48     }
49 
50     friend void output(const Vector& vec) {
51         for (size_t i = 0; i < vec.size; i++) {
52             std::cout << vec.data[i] << " ";
53         }
54         std::cout << std::endl;
55     }
56 };
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<fstream>
 3 
 4  void output(std::ostream &out) {
 5   for (int i = 0; i <= 26; i++) {
 6           out.width(2);
 7           if (i == 0) out << ' ';
 8           else out << i;
 9           for (int j = 0; j <= 26; j++) {
10              out << ' ';
11              if (i == 0) out << (char)('a' + (i + j) % 26);
12              else out << (char)('A' + (i + j) % 26);
13          }
14          out << '\n';
15      }
16  }
17  void output() {
18      output(std::cout);
19      std::ofstream ofile;
20      ofile.open("cipher_key.txt");
21      output(ofile);
22    ofile.close();
23  }
24 int main() {
25    output();
26  }
task5.cpp源码
运行结果截图

 

posted on 2023-12-18 01:22  陈少秋  阅读(13)  评论(0编辑  收藏  举报