Vector.hpp
1 #ifndef VECTOR_HPP 2 #define VECTOR_HPP 3 4 #include <iostream> 5 #include <stdexcept> 6 7 template<class T> 8 class Vector { 9 private: 10 T* arr; 11 int size; 12 13 public: 14 Vector() : arr(nullptr), size(0) {} 15 16 Vector(int n) : size(n) { 17 arr = new T[size]; 18 } 19 20 Vector(int n, const T& value) : size(n) { 21 arr = new T[size]; 22 for (int i = 0; i < size; i++) { 23 arr[i] = value; 24 } 25 } 26 27 Vector(const Vector<T>& other) { 28 size = other.size; 29 arr = new T[size]; 30 for (int i = 0; i < size; i++) { 31 arr[i] = other.arr[i]; 32 } 33 } 34 35 ~Vector() { 36 delete[] arr; 37 } 38 39 int get_size() const { 40 return size; 41 } 42 43 T& at(int index) { 44 if (index < 0 || index >= size) { 45 throw std::out_of_range("Index out of range"); 46 } 47 return arr[index]; 48 } 49 50 T& operator[](int index) { 51 return at(index); 52 } 53 54 Vector<T>& operator=(const Vector<T>& other) { 55 if (this != &other) { 56 delete[] arr; 57 size = other.size; 58 arr = new T[size]; 59 for (int i = 0; i < size; i++) { 60 arr[i] = other.arr[i]; 61 } 62 } 63 return *this; 64 } 65 66 friend void output(const Vector<T>& vec) { 67 for (int i = 0; i < vec.size; i++) { 68 std::cout << vec.arr[i] << " "; 69 } 70 std::cout << std::endl; 71 } 72 }; 73 74 #endifView Code
task4.cpp
1 #include <iostream> 2 #include "Vector.hpp" 3 4 void test() { 5 using namespace std; 6 7 int n; 8 cin >> n; 9 10 Vector<double> x1(n); 11 for(auto i = 0; i < n; ++i) 12 x1.at(i) = i * 0.7; 13 14 output(x1); 15 16 Vector<int> x2(n, 42); 17 Vector<int> x3(x2); 18 19 output(x2); 20 output(x3); 21 22 x2.at(0) = 77; 23 output(x2); 24 25 x3[0] = 999; 26 output(x3); 27 } 28 29 int main() { 30 test(); 31 }View Code
运行结果截图
task5.cpp
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 c,b; 12 if(i==0&&j==0){ 13 char d = ' '; 14 out<<setw(2)<<d; 15 } 16 else if(j==0&&i!=0){ 17 out<<setw(2)<<i; 18 } 19 else if(i==0&&j!=0){ 20 char c='a'+j-1; 21 out<<setw(2)<<c; 22 } 23 else if(i!=0&&j!=0){ 24 char b=(i+j-1+26)%26+'A'; 25 out<<setw(2)<<b; 26 } 27 } 28 out<<endl; 29 } 30 } 31 int main(){ 32 output(cout); 33 34 ofstream outFile("cipher_key.txt"); 35 output(outFile); 36 outFile.close(); 37 38 return 0; 39 }View Code
运行结果截图
标签:文件,arr,int,Vector,实验,output,include,模板,size From: https://www.cnblogs.com/chenxiaolong202083290491/p/17908943.html