task4源代码:
1 #pragma once 2 3 #include<iostream> 4 #include<stdexcept> 5 #include<cassert> 6 #include<iomanip> 7 8 using namespace std; 9 10 template <typename T> 11 class Vector { 12 public: 13 Vector(int size){ 14 if(size < 0) { 15 throw length_error("Vector constructor:negative size"); 16 } 17 this->size = size; 18 ptr = new T[this->size]; 19 } 20 21 Vector(int size, T value) { 22 if(size < 0) { 23 throw length_error("Vector construtor:negative size"); 24 } 25 this->size = size; 26 ptr = new T[size]; 27 for(auto i=0;i<size;i++) { 28 ptr[i] = value; 29 } 30 } 31 32 Vector(const Vector<T>& x) { 33 size = x.size; 34 ptr = new T[size]; 35 for(auto i=0;i<size;i++) { 36 ptr[i] = x.ptr[i]; 37 } 38 } 39 40 ~Vector() { delete[] ptr; } 41 42 int get_size() { return size; } 43 44 T& at(int i) const { 45 assert(i >= 0 && i < size); 46 return(ptr[i]); 47 } 48 49 T& operator[](int i) { return ptr[i]; } 50 51 friend void output(Vector<T> x) { 52 for(auto i=0;i<x.get_size();i++) { 53 cout << x.at(i) << ", "; 54 } 55 cout << "\t\t\n"; 56 } 57 58 private: 59 int size; 60 T* ptr; 61 };Vector.hpp
1 #include"Vector.hpp" 2 #include<iostream> 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 15 output(x1); 16 17 Vector<int> x2(n, 42); 18 Vector<int> x3(x2); 19 20 output(x2); 21 output(x3); 22 23 x2.at(0) = 77; 24 output(x2); 25 26 x3[0] = 999; 27 output(x3); 28 } 29 30 int main() { 31 test(); 32 }task4.cpp
task4运行结果:
task5源代码:
1 #include<iostream> 2 #include<fstream> 3 #include<iomanip> 4 5 using namespace std; 6 7 void output(std::ostream& output) { 8 output << " "; 9 for(int i=97;i<123;i++) { 10 output << setw(2) << char(i); 11 } 12 output << endl; 13 14 for(int i=1;i<=26;i++) { 15 output << setw(2) << i; 16 17 for(int j=i;j<i+26;j++) { 18 output << setw(2) << char(65 + j % 26); 19 } 20 output << endl; 21 } 22 } 23 24 int main() { 25 ofstream out; 26 output(cout); 27 out.open("cipher_key.txt"); 28 output(out); 29 return 0; 30 }task5.cpp
task5运行结果:
标签:int,Vector,实验,output,include,ptr,size From: https://www.cnblogs.com/atry/p/17904946.html