实验任务4
Vector.hpp
1 #pragma once 2 3 #include <iostream> 4 #include <stdexcept> 5 6 using namespace std; 7 8 template <typename T> 9 10 class Vector { 11 private: 12 T* data; 13 size_t size; 14 15 public: 16 Vector(size_t sz) : size(sz) { 17 data = new T[size]; 18 } 19 20 Vector(size_t sz, const T& value) : size(sz) { 21 data = new T[size]; 22 for (size_t i = 0; i < size; ++i) 23 { 24 data[i] = value; 25 } 26 } 27 28 Vector(const Vector& other) : size(other.size) { 29 data = new T[size]; 30 for (size_t i = 0; i < size; ++i) 31 { 32 data[i] = other.data[i]; 33 } 34 } 35 36 ~Vector() { 37 delete[] data; 38 } 39 40 size_t get_size() const { 41 return size; 42 } 43 44 T& at(size_t index) { 45 if (index < size) 46 { 47 return data[index]; 48 } 49 else 50 { 51 throw out_of_range("Index out of range"); 52 } 53 } 54 55 T& operator[](size_t index) { 56 if (index < size) 57 { 58 return data[index]; 59 } 60 else 61 { 62 throw out_of_range("Index out of range"); 63 } 64 } 65 66 friend void output(const Vector& vec) { 67 for (size_t i = 0; i < vec.size; ++i) 68 { 69 cout << vec.data[i] << ' '; 70 } 71 cout << endl; 72 } 73 };View 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 * 1.414; 13 14 output(x1); 15 16 Vector<int> x2(n, 27); 17 Vector<int> x3(x2); 18 19 output(x2); 20 output(x3); 21 22 x2.at(0) = 50; 23 output(x2); 24 25 x3[0] = 999; 26 output(x3); 27 } 28 29 int main() { 30 test(); 31 }View Code
运行测试结果
实验任务5
task5.cpp
1 #include <iostream> 2 #include <iomanip> 3 #include <fstream> 4 5 using namespace std; 6 7 void output(ostream &out) { 8 9 const int numLines = 26; 10 11 for (int i = 0; i < numLines; ++i) { 12 out << setw(2) << right << i + 1 << ' '; 13 for (int j = 0; j < 26; ++j) 14 { 15 char ch = 'A' + (i + j) % 26; 16 out << ch << ' '; 17 } 18 out << endl; 19 } 20 } 21 22 int main() { 23 24 cout << "输出矩阵:\n" 25 << " a b c d e f g h i j k l m n o p q r s t u v w x y z" 26 << endl; 27 28 output(cout); 29 30 ofstream outFile("cipher_key.txt"); 31 32 if (outFile.is_open()) 33 { 34 output(outFile); 35 outFile.close(); 36 } 37 else 38 { 39 return 1; 40 } 41 42 return 0; 43 }View Code
运行测试结果
标签:文件,out,Vector,实验,output,include,data,模板,size From: https://www.cnblogs.com/rssn/p/17894051.html