实验任务4 Vector.hpp
#ifndef VECTOR_HPP #define VECTOR_HPP #include <iostream> #include <stdexcept> template <typename T> class Vector; template <typename U> void output(const Vector<U>& vec); template <typename T> class Vector { private: T* elements; size_t size; public: Vector(size_t size) : size(size) { elements = new T[size]; } Vector(size_t size, const T& value) : size(size) { elements = new T[size]; for (size_t i = 0; i < size; ++i) { elements[i] = value; } } Vector(const Vector& other) : size(other.size) { elements = new T[size]; for (size_t i = 0; i < size; ++i) { elements[i] = other.elements[i]; } } ~Vector() { delete[] elements; } size_t get_size() const { return size; } T& at(size_t index) { if (index >= size) { throw std::out_of_range("越界"); } return elements[index]; } T& operator[](size_t index) { if (index >= size) { throw std::out_of_range("越界"); } return elements[index]; } friend void output<T>(const Vector<T>& vec); }; template <typename U> void output(const Vector<U>& vec) { for (size_t i = 0; i < vec.size; ++i) { std::cout << vec.elements[i] << " "; } std::cout << std::endl; } #endifView 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
实验任务5 task5.cpp
#include<iostream> #include<fstream> #include<iomanip> using namespace std; void output(std::ostream& output) { output << " "; for (int i = 97; i < 123; i++) { output << setw(2) << char(i); } output << endl; for (int i = 1; i <= 26; i++) { output << setw(2) << i; int j; for (j=i;j<i+26;j++) { output<<setw(2)<<char(65+j%26); } output << endl; } } int main() { ofstream out; output(cout); out.open("cipher_key.txt"); output(out); return 0; }View Code
标签:文件,elements,const,Vector,实验,output,include,模板,size From: https://www.cnblogs.com/mzxfcyt/p/17899944.html