实验任务4
#pragma once #include<iostream> #include<stdexcept> using namespace std; template<typename T> class Vector { public: Vector(int n); Vector(int n, T value); Vector(const Vector<T> &vi); ~Vector(); int get_size() const {return size;} T& at(int index); T& operator[](int index); template<typename T1> friend void output(const Vector<T1> &v); private: int size; T *ptr; }; template<typename T> Vector<T>::Vector(int n): size{n} { if(n < 0) throw length_error("Vector constructor:negative size"); ptr = new T[size]; } template<typename T> Vector<T>::Vector(int n, T value): size{n} { if(n < 0) throw length_error("Vector constructor:negative size"); ptr = new T[size]; for(auto i = 0; i < size; ++i) ptr[i] = value; } template<typename T> Vector<T>::Vector(const Vector<T> &vi): size{vi.size}, ptr{new T[size]} { for(auto i = 0; i < size; ++i) ptr[i] = vi.ptr[i]; } template<typename T> Vector<T>::~Vector() { delete[] ptr; } template<typename T> T& Vector<T>::at(int index) { if(index < 0 || index >= size) throw out_of_range("Vector Index out of range"); return ptr[index]; } template<typename T> T& Vector<T>::operator[](int index) { if(index < 0 || index >= size) throw out_of_range("Vector index out of range"); return ptr[index]; } template<typename T1> void output(const Vector<T1> &v) { for(auto i = 0; i < v.get_size(); ++i) cout << v.ptr[i] << ", "; cout << "\b\b \n"; }Vector.hpp
#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(); }task4.cpp
实验任务5
#include <fstream> #include <iomanip> void output(std::ostream &out) { out << std::setw(4) << 'a'; for (char i = 'b'; i <= 'z'; i++) { out << std::setw(2) << i; } out << std::endl; int n = 26; char start_letter = 'A'; for (int i = 1; i <= n; i++) { out << std::setw(2) << i << " "; for (int j = 0; j < n; j++) { char letter = start_letter + (i + j) % n; out << letter << " "; } out << std::endl; } } int main() { output(std::cout); std::cout << std::endl; std::ofstream out; out.open("cipher_key.txt"); if (!out.is_open()) { std::cout << "fail to open file " << "cipher_key.txt" << std::endl; } output(out); out.close(); return 0; }task5.cpp
标签:index,template,int,Vector,实验,IO,ptr,模板,size From: https://www.cnblogs.com/Lucky-19/p/17895727.html