首页 > 其他分享 >实验6 模板类、文件I/O和异常处理

实验6 模板类、文件I/O和异常处理

时间:2024-12-17 19:31:08浏览次数:8  
标签:std 文件 const Vector 实验 using include 模板 size

任务4:

Vector.hpp

#pragma once

#include<iostream>
#include<stdexcept>
using namespace std;
template<typename T>
class Vector{
public:
Vector(size_t n = 0) : size_(n) {
        if (n < 0) {
            throw std::length_error("数组大小不能为负");
        }
        try {
            elements = new T[n];
        } catch (const std::bad_array_new_length&) {
            // 重新抛出更合适的异常或者进行其他处理
            throw std::length_error("数组大小不能为负");
        }
    }

    // 构造函数,指定大小并初始化为给定值
    Vector(size_t n, const T& value) : size_(n) {
        if (n < 0) {
            throw std::length_error("数组大小不能为负");
        }
        try {
            elements = new T[n];
            for (size_t i = 0; i < n; ++i) {
                elements[i] = value;
            }
        } catch (const std::bad_array_new_length&) {
            // 重新抛出更合适的异常或者进行其他处理
            throw std::length_error("数组大小不能为负");
        }
    }
    Vector(const Vector<T>& 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 out_of_range("下标越界");
        }
        return elements[index];
    }
    
    T& operator[](size_t index){
        if(index>=size_){
            throw out_of_range("下标越界");
        }
        return elements[index];
    }
    
    friend output(const Vector<T>& v){
        for(size_t i=0;i<v.size_;++i){
            cout<<v.elements[i]<<" ";
        }
        cout<<endl;
    }
    
private:
    size_t size_;
    T *elements;
};    
Vector.hpp

task4.cpp

#include <iostream>
#include "Vector.hpp"

void test1() {
    using namespace std;

    int n;
    cout << "Enter n: ";
    cin >> n;
    
    Vector<double> x1(n);
    for(auto i = 0; i < n; ++i)
        x1.at(i) = i * 0.7;

    cout << "x1: "; output(x1);

    Vector<int> x2(n, 42);
    const Vector<int> x3(x2);

    cout << "x2: "; output(x2);
    cout << "x3: "; output(x3);

    x2.at(0) = 77;
    x2.at(1) = 777;
    cout << "x2: "; output(x2);
    cout << "x3: "; output(x3);
}

void test2() {
    using namespace std;

    int n, index;
    while(cout << "Enter n and index: ", cin >> n >> index) {
        try {
            Vector<int> v(n, n);
            v.at(index) = -999;
            cout << "v: "; output(v);
        }
        catch (const exception &e) {
            cout << e.what() << endl;
        }
    }
}

int main() {
    cout << "测试1: 模板类接口测试\n";
    test1();

    cout << "\n测试2: 模板类异常处理测试\n";
    test2();
}
View Code

运行结果截图

任务5:

 task5.cpp

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include<iomanip>
#include<algorithm>

using std::string;
using std::ostream;
using std::istream;
using std::setw;
using std::setprecision;
using std::setiosflags;
using std::ios_base;

class People{
    private:
        string no;//学号
        string name;//姓名
        string major;//专业
        int score;//分数
         
    public:
    People()=default;
    ~People()=default;
    int get_score() const{return score;} 
    string get_string() const{return major;}
    
    friend ostream& operator<<(ostream &out, const People &c);
    friend istream& operator>>(istream &in, People &c);
};

//重载<<
ostream& operator<<(ostream &out, const People &c) {
    out << setiosflags(ios_base::left);
    out << setw(15) << c.no
        << setw(15) << c.name
        << setw(15) << c.major
        << setw(15) << c.score; 
    return out;
}

//重载>>
istream& operator>>(istream &in, People &c) {
    in >> c.no >> c.name >> c.major >> c.score;
    return in;
}

//专业按字典序排序 相同按分数排序 
bool compare_by_order(const People &p1,const People &p2) {
    if(p1.get_string()<p2.get_string())
    return true;
    
    if(p1.get_string()==p2.get_string())
    return p1.get_score()>p2.get_score();
    
    return false;
}

// 把vector<People>对象中的元素插入到输出流out
void output(std::ostream &out, const std::vector<People> &v) {
    for(auto &i: v)
    out << i << std::endl;
}

// 把vector<People>对象中的元素写到filename文件中
void save(const std::string &filename, std::vector<People> &v) {
    using std::ofstream;
    ofstream out(filename);
    if(!out.is_open()) {
    std::cout << "fail to open file to write\n";
    return;
    }
    output(out, v);
    out.close();
}

// 从文件filename读取参赛选手信息到vector<People>对象
void load(const std::string &filename, std::vector<People> &v) {
    using std::ifstream;
    ifstream in(filename);
    if(!in.is_open()) {
        std::cout << "fail to open file to read\n";
    return;
}
std::string title_line;
getline(in, title_line); // 跳过标题行
People t;
while(in >> t)
    v.push_back(t);
    in.close();
}

void test(){
    using namespace std;
    
    vector<People> v;
    
    load("data5.txt",v);//从文件加载
    sort(v.begin(),v.end(),compare_by_order);//排序
    output(cout,v);//输出到屏幕
    save("ans5.txt",v);//保存到文件 
}

int main(){
    test();
}
task5.cpp

运行结果截图

 

标签:std,文件,const,Vector,实验,using,include,模板,size
From: https://www.cnblogs.com/pure-w/p/18613015

相关文章

  • 实验六
    实验任务5:(1)代码部分:1#pragmaonce2#include<iostream>3#include<cstring>45usingnamespacestd;67template<classT>8classVector{9public:10Vector(intn,intvalue=0);11Vector(constVector&......
  • 实验6 模板类、文件I/O和异常处理
    task4Vector.hpp1#pragmaonce23#include<iostream>4#include<stdexcept>56usingstd::cout;7usingstd::endl;89template<typenameT>10classVector{11public:12Vector(intsize0=0);13Vector(intsiz......
  • 实验6 模板类、文件I/O和异常处理
    1.实验任务4Vector.hpp1#pragmaonce2#include<iostream>3#include<stdexcept>45usingnamespacestd;67template<typenameT>8classVector{9public:10Vector(intn);11Vector(intn,Tvalue);12Vector(c......
  • 实验6 模板类、文件I/O和异常处理
    task4:Vector.hpp#pragmaonce#include<iostream>#include<stdexcept>usingnamespacestd;template<typenameT>classVector{public:Vector(intsize,intvalue=0):size{size}{if(size<0)throwlength_error(......
  • vue导出.csv文件
    //安装papaparsenpmipapaparse--saveimport*asPapaparsefrom"papaparse";/***默认导出数据头部*贴别注意格式的问题,不然导出的.cvs文件和上传的.cvs文件解析出来的结果会不一样数组的长度必须保持一致,不够的用空字符站位,如红色部分*/constdefaultCvsDa......
  • OPP实验六
    任务一、 对于约束性模板友元和非约束性模板友元,在语法上的区别在于,templete<typenameT>T的名字与类中是不一样就是非约束性就是不受类的模板的影响相互独立的。由于这里出现了两种的输出方式,通过ostream是iostream和fostream的基类,就可以一个重载使用两个,方便了一点。......
  • 程序设计实验6
    实验任务1 实验任务2实验任务3实验任务41#pragmaonce2#include<iostream>3#include<stdexcept>4#include<iomanip>5usingnamespacestd;6template<typenameT>7classVector{8private:9intsize;10T*ptr;11public:12V......
  • 实验六
    任务4vector.hpp#pragmaonce#include<iostream>#include<stdexcept>usingstd::cout;usingstd::endl;template<typenameT>classVector{ public: Vector(ints); Vector(ints,Tv); Vector(constVector<T>&v); ~Vector();......
  • 实验六
    task4:代码:1#pragmaonce23#include<iostream>4#include<stdexcept>5#include<cmath>67usingnamespacestd;89template<typenameT>10classVector{11private:12intsize;13T*ptr;14......
  • 实验六
    实验任务四代码vector.hpp1#ifndefVECTOR_HPP2#defineVECTOR_HPP34#include<stdexcept>5#include<iostream>//确保可以使用std::cout和std::endl67template<typenameT>8classVector{9private:10T*data_;11......