实验四:
Vector.hpp:
// #pragma once #include <iostream> #include <stdexcept> using namespace std; template <typename T> class Vector { private: T* data; int size; public: Vector(int sz = 0, const T& value = T()); Vector(const Vector& other); ~Vector(); int get_size() const; T& at(int index); T& operator[](int index); template <typename T1> friend void output(const Vector<T1>& v); }; template <typename T> Vector<T>::Vector(int sz, const T& value) : size(sz) { data = new T[size]; for (int i = 0; i < size; ++i) { data[i] = value; } } template <typename T> Vector<T>::Vector(const Vector& other) : size(other.size) { data = new T[size]; for (int i = 0; i < size; ++i) { data[i] = other.data[i]; } } template <typename T> Vector<T>::~Vector() { delete[] data; } template <typename T> int Vector<T>::get_size() const { return size; } template <typename T> T& Vector<T>::at(int index) { if (index >= size) { throw std::out_of_range("Index out of range"); } return data[index]; } template <typename T> T& Vector<T>::operator[](int index) { if (index >= size) { throw out_of_range("Index out of range"); } return data[index]; } template <typename T1> void output(const Vector<T1>& v) { for (int i = 0; i < v.size; ++i) { cout << v.data[i] << ","; } cout << "\b \b" << endl; }View Code
task4.cpp:
#include <iostream> #include "Vector.hpp" void test() { using namespace std; int n; cin >> n; Vector<double> x1(n); for(auto i = 0; i < n; ++i) x1.at(i) = i * 0.7; output(x1); Vector<int> x2(n, 42); Vector<int> x3(x2); output(x2); output(x3); x2.at(0) = 77; output(x2); x3[0] = 999; output(x3); } int main() { test(); }View Code
测试结果:
实验五:
task5:
#include <iostream> #include <fstream> #include <iomanip> using namespace std; void output(ostream& out) { for (int i = 0; i <= 26; ++i) { if (i == 0) { out << " "; for (char ch = 'a'; ch <= 'z'; ++ch) { out << ch << ' '; } out << endl; continue; } out << setw(2) << i << ' '; for (int j = 0; j < 26; ++j) { out << char('A' + (j + i) % 26) << ' '; } out << endl; } } int main() { output(cout); ofstream out("cipher_key.txt"); if (out) { output(out); } else if (!out.is_open()) { cout << "Fail to open the file." << endl; } out.close(); return 0; }View Code
结果:
标签:文件,const,int,Vector,实验,template,data,模板,size From: https://www.cnblogs.com/202283230013nuister/p/17897852.html