实验6 模板类和文件io

task4

Vector.cpp

#pragma once
using namespace std;
template <typename T>
class Vector{
public:
    Vector(int n);
    Vector(int n, T v);
    ~Vector();
    Vector(const Vector<T>& V);
    int get_size() {
        return size;
    }
    T& at(int i) {
            return x[i];
    }
    T& operator[](int i) {
            return this->x[i];
    }
    template <typename T1>
    friend void output(Vector<T1> V);
private:
    T* x;
    int size;
};
template <typename T>
Vector<T>::Vector(int n) :size(n) {
    x = new T[n];
}
template <typename T>
Vector<T>::~Vector() {
    delete[]x;
}
template <typename T>
Vector<T>::Vector(int n, T v) :size(n) {
    x = new T[n];
    for (int i = 0; i < n; i++)
        x[i] = v;
}
template <typename T>
Vector<T>::Vector(const Vector<T>& V) {
    size = V.size;
    x = new T[V.size];
    for (int i = 0; i < V.size; i++)
        x[i] = V.x[i];
}
template <typename T1>
void output(Vector<T1> V) {
    for (int i = 0; i < V.size; i++)
        cout << V.x[i] << " ";
    cout << endl;
}

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();
}

 task5

task5.cpp

#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
#include<vector>
void output(std::ostream& out) {
    out << "  ";
    char a='a';
    while (a <= 'z' && a >= 'a') {
        out << setw(2) << a;
        a++;
    }
    out << endl;
    a = 'B';
    for (int i = 1; i <= 25; i++) {
        out << setw(2)<<right << i << " ";
        char b = a;
        while (b<='Z') {
            out << setiosflags(ios_base::right) << b<<" ";
            b++;
        }
        b = 'A';
        while (b<= a-1) {
            out << setiosflags(ios_base::right) << b<<" ";
            b++;
        }
        out << endl;
        a++;
    }
    a = 'A';
    out << setw(2) <<right<< "26 ";
    while (a <= 'Z') {
        out << setiosflags(ios_base::right) << a <<" ";
        a++;
    }
    out << endl;
}
int main() {
    output(cout);
    ofstream out;
    out.open("cipher_key.txt",ios::out);
    output(out);
    out.close();
}

 

 

 

posted @ 2022-12-04 15:50  费远航  阅读(10)  评论(0编辑  收藏  举报