实验六
1 #include <iostream> 2 #include "Vector.hpp" 3 using namespace std; 4 5 template<typename T> 6 void output(const Vector<T>& v){ 7 for(auto i=0;i<v.get_size();i++){ 8 cout << v.at(i) << ", "; 9 10 11 } 12 cout << "\b\b \n"; 13 } 14 15 void test() { 16 using namespace std; 17 int n; 18 cin >> n; 19 Vector<double> x1(n); 20 for(auto i = 0; i < n; ++i) 21 x1.at(i) = i * 0.7; 22 output(x1); 23 Vector<int> x2(n, 42); 24 Vector<int> x3(x2); 25 output(x2); 26 output(x3); 27 x2.at(0) = 77; 28 output(x2); 29 x3[0] = 999; 30 output(x3); 31 } 32 int main() { 33 test(); 34 }
1 #include <iostream> 2 #include <stdexcept> 3 #include <ostream> 4 5 template <typename T> 6 class Vector { 7 public: 8 Vector() : data(nullptr), size(0) {} 9 10 explicit Vector(int size) : data(new T[size]), size(size) {} 11 12 Vector(int size, const T& value) : data(new T[size]), size(size) { 13 for (int i = 0; i < size; ++i) { 14 data[i] = value; 15 } 16 } 17 18 Vector(const Vector<T>& other) : data(new T[other.size]), size(other.size) { 19 for (int i = 0; i < size; ++i) { 20 data[i] = other.data[i]; 21 } 22 } 23 24 ~Vector() { 25 delete[] data; 26 } 27 28 int get_size() const { 29 return size; 30 } 31 32 T& at(int index) { 33 if (index < 0 || index >= size) { 34 throw std::out_of_range("索引越界"); 35 } 36 return data[index]; 37 } 38 39 T& operator[](int index) { 40 return at(index); 41 } 42 43 friend void output(const Vector<T>& v) { 44 for (int i = 0; i < v.size; ++i) { 45 std::cout << v.data[i] << " "; 46 } 47 std::cout << std::endl; 48 } 49 50 private: 51 T* data; 52 int size; 53 }; 54 55 void test() { 56 using namespace std; 57 int n; 58 cin >> n; 59 60 Vector<double> x1(n); 61 for (auto i = 0; i < n; ++i) 62 x1.at(i) = i * 0.7; 63 output(x1); 64 65 Vector<int> x2(n, 42); 66 Vector<int> x3(x2); 67 output(x2); 68 output(x3); 69 70 x2.at(0) = 77; 71 output(x2); 72 x3[0] = 999; 73 output(x3); 74 75 cout << "x3.get_size() = " << x3.get_size() << endl; 76 } 77 78 int main() { 79 test(); 80 return 0; 81 }
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 char m, n; 11 if (i == 0 && j == 0) { 12 char t = ' '; 13 out << setw(2) << t; 14 } else if (j == 0 && i != 0) { 15 out << setw(2) << i; 16 } else if (i == 0 && j != 0) { 17 char m = 'a' + j - 1; 18 out << setw(2) << m; 19 } else if (i != 0 && j != 0) { 20 char n = (i + j - 1 + 26) % 26 + 'A'; 21 out << setw(2) << n; 22 } 23 } 24 out << endl; 25 } 26 } 27 28 int main() { 29 output(cout); 30 31 ofstream outFile("cipher_key.txt"); 32 if (outFile.is_open()) { 33 output(outFile); 34 outFile.close(); 35 } else { 36 cout << "Unable to open file."; 37 } 38 39 return 0; 40 }