实验任务4
Vector.hpp源代码
1 #include <iostream> 2 #include <stdexcept> 3 4 template <typename T> 5 class Vector { 6 private: 7 int size; 8 T *vec; 9 public: 10 Vector<T>() = default; 11 Vector<T>(int s); 12 Vector<T>(int s, T t); 13 Vector<T>(const Vector<T> &v); 14 ~Vector<T>(); 15 int get_size() const; 16 T& at(int i); 17 T& operator[](int i); 18 template <typename T1> 19 friend void output(const Vector<T1> &v); 20 }; 21 template <typename T> 22 Vector<T>::Vector(int s) 23 : size{s} { 24 vec = new T[s]; 25 } 26 template <typename T> 27 Vector<T>::Vector(int s, T t) 28 : size{s} { 29 vec = new T[s]; 30 for (int i = 0; i < s; i++) 31 vec[i] = t; 32 } 33 template <typename T> 34 Vector<T>::Vector(const Vector<T> &v) 35 : size{v.size} { 36 vec = new T[v.size]; 37 for (int i = 0; i < v.size; i++) 38 vec[i] = v.vec[i]; 39 } 40 template <typename T> 41 Vector<T>::~Vector() { 42 delete[] vec; 43 } 44 template <typename T> 45 int Vector<T>::get_size() const { 46 return size; 47 } 48 template <typename T> 49 T& Vector<T>::at(int i) { 50 if (i > size) throw std::out_of_range("下标越界"); 51 else return vec[i]; 52 } 53 template <typename T> 54 T& Vector<T>::operator[](int i) { 55 if (i > size) throw std::out_of_range("下标越界"); 56 else return vec[i]; 57 } 58 template <typename T1> 59 void output(const Vector<T1> &v) { 60 for (int i = 0; i < v.size; i++) 61 std::cout << v.vec[i] << ", "; 62 std::cout << "\b\b \n"; 63 }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 * 0.618; 13 14 output(x1); 15 16 Vector<int> x2(n, 777); 17 Vector<int> x3(x2); 18 19 output(x2); 20 output(x3); 21 22 x2.at(0) = 42; 23 output(x2); 24 25 x3[0] = 666; 26 output(x3); 27 } 28 29 int main() { 30 test(); 31 }View Code 运行测试截图
实验任务5
task5.cpp源码
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 }View Code
运行测试截图
标签:文件,int,Vector,实验,vec,template,output,模板,size From: https://www.cnblogs.com/ffhfAdjFH7Vr/p/17897120.html