课程设计

一.文本文件单词统计

1.1问题描述

假设有如下的英文文本文档:(此处为太原理工大学学校简介英文版)
TAIYUAN UNIVERSITY OF TECHNOLOGY

Taiyuan University of Technology (TUT) has its history traced all the way back to the Western Learning School of Shanxi Grand Academy (1902), which was one of the three earliest national universities in China. With the tradition and development of over 100 years, TUT is now a general university with engineering as the major, sciences and technology integrated and coordinate development of multiple disciplines. It is a university that is included in the “Project 211” — the national higher education promotion program for 100 top universities in China.
……
Recollecting the centennial history, generations of TUT have created its mission and glory of a century with responsibility and confidence; expecting the promising tomorrow, over 30,000 TUT students and faculty are producing splendor and perspectives by their wisdom and diligence. In the new era, Taiyuan University of Technology, following the Conception of Scientific Development, is determined to further the reformation on education, to reinforce the teaching management so as to upgrade its teaching and researching levels. Taiyuan University of Technology will be turning itself into a research-based university.
设计C或C++程序,统计在这样的英文文本文件中,出现了多少个单词,每个单词出现了几次。连续的英文字
符都认为单词(不包括数字),单词之间用空格或标点符号分隔。

1.2设计需求及分析

要统计英文文本文件中出现了哪些单词,就要从文件中读取字符,读取出来的连续英文字符认为是一个单词,遇空格或标点符号单词结束。
使用线性表记录单词以及每个单词出现的次数。线性表中的单词按字典顺序存储。

线性表的顺序存储结构如下:
#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
typedef struct{
char word[21] //存储单词,不超过20个字符
int count; //单词出现的次数
} ElemType;
typedef struct{
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量
} Seqlist;

1.3设计功能的实现
#include <iostream>

#define LIST_INIT_SIZE 10

#include <fstream>

using namespace std;

class ElemType {
public:
    int count;
    string word;

    ElemType() : count(0) {}

    virtual ~ElemType() {
    }
};

class SeqList {
private:
    ElemType *elem;
    int length;
    int listSize;

    int LocateElem(string &s) {//确定增加的单词,若是没有,则返回插入新单词的位置
        int low = 0;
        int high;
        int mid;
        high = length - 1;
        while (low <= high) {
            mid = (low + high) / 2;
            if (s.compare(elem[mid].word) == 0) {
                elem[mid].count++;
                return -1;
            } else if (s.compare(elem[mid].word) < 0)
                high = mid - 1;
            else
                low = mid + 1;
        }
        return low;
    }

public:
    virtual ~SeqList() {
        delete[] elem;
    }

    SeqList() {//list的构造函数
        listSize = LIST_INIT_SIZE;
        elem = new ElemType[listSize];
        if (elem == nullptr) {
            return;
        }
        length = 0;
        listSize = listSize;

    }

    bool InsertList(string &s) {//插入节点
        int i = LocateElem(s);
        if (i == -1) {
            return false;
        } else {

            if (length >= listSize) {
                listSize *= 1.2;
                ElemType *newElem = new ElemType[listSize];;
                for (int i = 0; i < length; i++) {
                    newElem[i] = elem[i];
                }
                delete[] elem;
                elem = newElem;
            }
            for (int j = length - 1; j >= i; j--) {
                elem[j + 1] = elem[j];
            }
            elem[i].count = 1;
            elem[i].word = s;
            length++;
        }
        return true;
    }

    void PrintList() {//打印
        int count = 0;
        for (int i = 0; i < length; i++) {
            count += elem[i].count;
            cout << elem[i].word << ":" << elem[i].count << endl;
        }
        cout << "总数为:" << count << endl;
    }
};


int main() {
    SeqList L = *new SeqList;
    ifstream ifs;
    ifs.open("E:\\Code\\C\\TYUT\\tyut.txt", ios::in);
    if (!ifs.is_open()) {
        cout << "打开失败" << endl;
        return 0;
    }
    char ch;//用于记录字符
    string str = "";//用于记录单词
    while ((ch = ifs.get()) != EOF) {
        if ((ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A')) {
            str += ch;
        } else {
            if (str != "") {
                L.InsertList(str);
            }
            str = "";
        }
    }
    L.PrintList();
    ifs.close();
    return 0;
}

1.4实例测试及运行结果

在这里插入图片描述

1.5实验心得

我用string保存了单词,就不能用malloc()和relloc()来开辟堆空间内存,应该用new来开辟堆空间,并且用当空间不够时,重新开辟较大存储空间并将数组转移.c++在内存管理方面比java要麻烦一些.

二.停车场管理

2.1问题描述

设停车场是一个可停放n辆汽车的狭长通道,且只有一个大门可供汽车进出。汽车在停车场内按车辆到达时间的先后顺序,依次由北向南排列(大门在最南端,最先到达的第一辆车停放在停车场的最北端),若停车场内已停满n辆汽车,则后来的汽车只能在门外的便道上等候,一旦有车开走,则排在便道上的第一辆车即可开入;当停车场内某辆车要离开时,在它之后进入的车辆必须先退出车场为它让路,待该辆车开出大门外,其他车辆再按原次序进入车场,每辆停放在车场的车在它离开停车场时必须按它停留的时间长短交纳费用。试为停车场编制按上述要求进行管理的模拟程序。

2.2设计需求及分析

以栈模拟停车场,以队列模拟车场外的便道,按照从终端读入的输入数据序列进行模拟管理。每一组输入数据包括三个数据项:汽车“到达”或“离去”信息、汽车牌照号码以及到达或离去的时刻。对每一组输入数据进行操作后的输出信息为:若是车辆到达,则输出汽车在停车场内或便道上的停车位置;若是车辆离去,则输出汽车在停车场内停留的时间和应交纳的费用(在便道上停留的时间不收费)。栈以顺序结构实现,队列以链表结构实现。****(两个栈和一个队列)****

2.3设计功能的实现
package Topic02;


public class Car {
    private String number;
    private String timeArrive;//到达时间
    private String timeLeave;//没用上

    public Car(String number, String timeArrive) {
        this.number = number;
        this.timeArrive = timeArrive;
        this.timeLeave ="";
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getTimeArrive() {
        return timeArrive;
    }

    public void setTimeArrive(String timeArrive) {
        this.timeArrive = timeArrive;
    }

    public String getTimeLeave() {
        return timeLeave;
    }

    public void setTimeLeave(String timeLeave) {
        this.timeLeave = timeLeave;
    }
}
package Topic02;


import java.util.Scanner;

public class Main {
    static final public int PRICE = 10;//每小时十块钱
    static public final Stack<Car> PARKINGLOT = new Stack<>();//停车场
    static public final Stack<Car> REVERSE = new Stack<>();//从停车场出去的车
    static public final Queue<Car> ROOD = new Queue<>();//便道

    static final public int CAPACITY = 2;//车位数量
    public static final Scanner SCANNER = new Scanner(System.in);

    static public void carEnter() {//车辆进入停车场
        System.out.println("输入车牌号:");
        String number = SCANNER.next();
        System.out.println("输入到来时间(xx:xx):");
        String arriveTime = SCANNER.next();
        Car car = new Car(number, arriveTime);
        //直接开进来
        if (PARKINGLOT.size() < CAPACITY) {
            PARKINGLOT.push(car);
            System.out.println("汽车所在停车场位置:" + PARKINGLOT.size());
        } else {//在外面等
            ROOD.enqueue(car);
            System.out.println("汽车所在便道位置:" + ROOD.size());
        }
    }

    static public void carLeave() {//车辆离开停车场
        System.out.println("输入车牌号:");
        String number = SCANNER.next();//车牌号
        while (true) {//车辆依次离开停车场
            Car car = PARKINGLOT.pop();
            if (car == null) {//没有这个车牌的车
                while (!REVERSE.isEmpty()) {

                    PARKINGLOT.push( REVERSE.pop());
                }
                System.err.println("没有该车");
                break;
            }
            if (car.getNumber().equals(number)) {//取出对应车牌的车
                System.out.println("输入离开时间");
                String leaveTime = SCANNER.next();
                System.out.println(processTime(car.getTimeArrive(), leaveTime));
                while (!REVERSE.isEmpty()) {
                    Car car1 = REVERSE.pop();
                    PARKINGLOT.push(car1);
                }
                if (!ROOD.isEmpty()) {
                    Car car1 = ROOD.dequeue();
                    car1.setTimeArrive(leaveTime);
                    PARKINGLOT.push(car1);
                    System.out.println("车牌:" + car1.getNumber() +"在"+car1.getTimeArrive() +
                            "时进入停车场,汽车所在停车场位置:" + PARKINGLOT.size());
                }
                break;
            } else {
                REVERSE.push(car);
            }
        }
    }

    static String processTime(String begin, String end) {//计算花了多少钱
        String[] b = begin.split(":");
        String[] e = end.split(":");
        Integer bh = Integer.parseInt(b[0]);
        int bm = Integer.parseInt(b[1]);
        Integer eh = Integer.parseInt(e[0]);
        int em = Integer.parseInt(e[1]);
        double times = (eh - bh) * 60 + em - bm;
        double price = (times / 60) * PRICE;
        return "时间为:" + times + "分钟  价格为:" + price + "元";
    }

    public static void main(String[] args) {
        System.out.println("停车场管理系统");
        while (true) {

            System.out.print("1.车辆进入");
            System.out.print("  2.车辆离开");
            System.out.print("  3.程序结束");
            System.out.println();
            int option = SCANNER.nextInt();
            switch (option) {
                case 1:
                    carEnter();
                    break;
                case 2:
                    carLeave();
                    break;
                default:
                    System.exit(0);
            }
        }
    }
}
package Topic02;


public class Queue<T> {
    private  static class Node<T>{//节点
        private T item;
        private Node next;
        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    /*
    进入的一段为head,出去的一端为last
     */
    private Node head;
    private Node last;
    private int N;

    public Queue() {
        head=null;
        last=new Node(null, null);


        N=0;
    }
    public boolean isEmpty(){//是否为空
        return N==0;
    }
    public int size(){//队列容量
        return N;

    }
    /*
    添加元素
     */
    public void enqueue(T t){//入队

        if(head==null){
            head=new Node(t,null);
            last.next=head;
        }else{

            Node<T> temp=new Node<>(t,null);
            head.next=temp;
            head=temp;
        }
        N++;

    }
    public T dequeue(){//出队
        if(isEmpty()){
            return null;
        }else{
            Node<T> temp=last.next;
            last=last.next;
            N--;
            return temp.item;

        }
    }
}

package Topic02;

/**
 * @author XiaoYL
 * @date 2020/6/15
 * 14:06
 */
public class Stack<T> {
    private static class Node<T>{//节点
        private T item;
        private Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    private Node head;//头节点
    private int N;

    public Stack() {
        head= new Node(null, null);
        N=0;
    }
    public boolean isEmpty(){//判断是否为空
        return N==0;
    }
    public void push(T t){//进栈
        Node<T> oldHead=head;
        head= new Node<T>(t, oldHead);
        N++;
    }
    public T pop(){//出栈
        if(!isEmpty()){
            N--;
            Node<T> oldHead=head;
            head=head.next;
            return oldHead.item;
        }else{
            return null;
        }
    }
    public int size()//栈的容量
    {
        return N;
    }

}

2.4实例测试及运行结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.5实验心得

单独定义栈,队列和car类,定义setter和getter方法,以保障程序的封装性.

在Main类中直接调用类方法,使程序井井有条,提高程序的可读性.

Java语言内存管理比c++方便.

三.交通咨询系统设计

3.1问题描述

在交通网络非常发达,交通工具和交通方式不断更新的今天,人们在出差、旅游或做其他出行时,不仅关心节省交通费用,而且对里程和所需要的时间等问题也感兴趣。对于这样一个人们关心的问题,可用一个图结构来表示交通网络系统,利用计算机建立一个交通咨询系统。图中的顶点表示城市,边表示城市之间的交通关系。这个交通系统可以回答出行旅客提出的各种路径选择问题。例如,问题之一:“一位旅客要从A城到B城,他希望选择一条途中中转次数最少的路线。”假设图中每一站都需要换车,那么这个问题反映到图上就是要找一条从顶点A到顶点B的所含边数目最少的路径。我们只需要从顶点A出发对图作广度优先搜索,一旦遇到顶点B就终止。由此所得广度优先生成树上,从根顶点A到顶点B的路径就是中转次数最少的路径。路径上A与B之间的顶点就是路径的中转站,但这只是一类最简单的图的最短路径问题。系统还可以回答诸如此类的等等的路径选择问题。

设计一个交通咨询系统,为出差、旅游或做其他出行的客人提供各种路径选择信息查询服务。

3.2设计需求及分析

设计一个交通咨询系统,能让旅客咨询从任一个城市顶点到另一城市顶点之间的最短路径(里程)或最低花费或最少时间等问题。对于不同的咨询要求,可输入城市间的路程或所需时间或所需费用。

本设计共分三部分,一是建立交通网络图的存储结构;二是解决单源最短路径问题;三是实现任两个城市顶点之间的最短路径问题

3.3设计功能的实现
package Topic03;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

abstract public class Graph<V, E> {
    /**
     * 返回边数
     *
     * @return
     */
    abstract int edgesSize();

    /**
     * 返回节点数
     *
     * @return
     */
    abstract int verticesSize();

    abstract void addVertex(V v);

    abstract void addEdge(V form, V to, E weight);

    abstract void addEdge(V form, V to);

    abstract Map<V, Map<V, PathInfo<V, E>>> Floyd();

    abstract Map<V, PathInfo<V, E>> Dijkstra(V begin);




    public static class PathInfo<V, E> {//保存路线的信息
        protected E weight;
        protected List<EdgeInfo<V, E>> edgeInfos = new LinkedList<>();
        public PathInfo() {}

        public PathInfo(List<EdgeInfo<V, E>> edgeInfos,E weight) {
            this.weight = weight;
            this.edgeInfos = edgeInfos;
        }

        public PathInfo(E weight) {
            this.weight = weight;
        }
        public E getWeight() {
            return weight;
        }
        public void setWeight(E weight) {
            this.weight = weight;
        }
        public List<EdgeInfo<V, E>> getEdgeInfos() {
            return edgeInfos;
        }
        public void setEdgeInfos(List<EdgeInfo<V, E>> edgeInfos) {
            this.edgeInfos = edgeInfos;
        }
        @Override
        public String toString() {
            return "PathInfo [weight=" + weight + ", \nedgeInfos=" + edgeInfos + "]";
        }
    }

    public static class EdgeInfo<V, E> {//保存边的信息
        private V from;
        private V to;
        private E weight;
        public EdgeInfo(V from, V to, E weight) {
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
        public V getFrom() {
            return from;
        }
        public void setFrom(V from) {
            this.from = from;
        }
        public V getTo() {
            return to;
        }
        public void setTo(V to) {
            this.to = to;
        }
        public E getWeight() {
            return weight;
        }
        public void setWeight(E weight) {
            this.weight = weight;
        }
        @Override
        public String toString() {
            return "EdgeInfo [from=" + from + ", to=" + to + ", weight=" + weight + "]\n";
        }
    }
}

package Topic03;

import java.util.Map;
import java.util.*;

/**
 * @author lalall
 */
public class MGraph<V, E> extends Graph<V, E> {
    private WeightWorker<E> weightWorker;

    public MGraph(WeightWorker<E> weightWorker) {
        this.weightWorker = weightWorker;//实例化MGraph时,也会实例化weightWorker,进而将接口中的方法重写
    }

    protected interface WeightWorker<E> {//
        int compare(E w1, E w2);

        E add(E w1, E w2);
    }

    private Map<V, Vertex<V, E>> VERTICES = new HashMap<>(); //保存节点
    private Set<Edge<V, E>> EDGES = new HashSet<>();//保存边



    @Override
    public int edgesSize() {
        return EDGES.size();
    }

    @Override
    public int verticesSize() {
        return VERTICES.size();
    }

    @Override
    public void addVertex(V v) {
        if (VERTICES.containsKey(v)) {
            return;
        }
        VERTICES.put(v, new Vertex<>(v));
    }

    @Override
    public void addEdge(V from, V to, E weight) {
        //先判断顶点是否存在
        Vertex<V, E> formVertex = VERTICES.get(from);
        if (formVertex == null) {
            formVertex = new Vertex<>(from);
            VERTICES.put(from, formVertex);
        }
        Vertex<V, E> toVertex = VERTICES.get(to);
        if (toVertex == null) {
            toVertex = new Vertex<>(to);
            VERTICES.put(to, toVertex);
        }
        Edge<V, E> edge = new Edge<>(formVertex, toVertex);
        edge.weight = weight;

        formVertex.outEdges.remove(edge);
        toVertex.inEdges.remove(edge);
        EDGES.remove(edge);
        formVertex.outEdges.add(edge);
        toVertex.inEdges.add(edge);
        EDGES.add(edge);
    }

    @Override
    public void addEdge(V form, V to) {
        addEdge(form, to, null);
    }

    @Override
    Map<V, PathInfo<V, E>> Dijkstra(V begin) {
        Vertex<V, E> beginVertex = VERTICES.get(begin);
        if (beginVertex == null) {
            return null;
        }
        //已经提出去的节点
        Map<V, PathInfo<V, E>> selectedPaths = new HashMap<>();
        //已经提出去的节点连接的节点
        Map<Vertex<V, E>, PathInfo<V, E>> paths = new HashMap<>();
        //对最开始的节点松弛
        for (Edge<V, E> edge : beginVertex.outEdges) {
            PathInfo<V, E> path = new PathInfo<>();
            path.weight = edge.weight;
            path.edgeInfos.add(edge.info());
            paths.put(edge.to, path);
        }
        while (!paths.isEmpty()) {
            Map.Entry<Vertex<V, E>, PathInfo<V, E>> minEntry = getMinPath(paths);
            //挑出当前的最短路径
            Vertex<V, E> minVertex = minEntry.getKey();
            selectedPaths.put(minVertex.value, minEntry.getValue());
            paths.remove(minVertex);

            //对minVertex的outEdges进行松弛操作
            for (Edge<V, E> edge : minVertex.outEdges) {
                if (selectedPaths.containsKey(edge.to.value)) {
                    continue;//若是已经起飞了,就不再松弛
                }
                //松弛操作
                relax(paths, minEntry, edge);
            }
        }
        selectedPaths.remove(begin);//若是双向的,则会反向松弛,就要把begin删除
        return selectedPaths;
    }

    //    //松弛操作
    private void relax(Map<Vertex<V, E>, PathInfo<V, E>> paths, Map.Entry<Vertex<V, E>, PathInfo<V, E>> minEntry, MGraph.Edge<V, E> edge) {
        //暂时的新的最短路径
        E newWeight = weightWorker.add(minEntry.getValue().weight, edge.weight);
        //旧的最短路径

        PathInfo<V, E> oldPath = paths.get(edge.to);

        // E oldWeight = oldPath.weight;
        if (oldPath == null || weightWorker.compare(newWeight, oldPath.weight) < 0) {
            PathInfo<V, E> pathInfo = new PathInfo<>();
            pathInfo.weight = newWeight;
            pathInfo.edgeInfos.addAll(minEntry.getValue().getEdgeInfos());
            pathInfo.edgeInfos.add(edge.info());
            paths.put(edge.to, pathInfo);
        }
    }

    @Override
    public Map<V, Map<V, PathInfo<V, E>>> Floyd() {
        Map<V, Map<V, PathInfo<V, E>>> paths = new HashMap<>();
 
        EDGES.forEach((Edge<V,E> edge)->{
            Map<V, PathInfo<V, E>> map = paths.get(edge.from.value);
            if (map == null) {
                map = new HashMap<>();
                paths.put(edge.from.value, map);
            }

            PathInfo<V, E> pathInfo = new PathInfo<>(edge.weight);
            pathInfo.edgeInfos.add(edge.info());
            map.put(edge.to.value, pathInfo);
        });
        //顺序不能乱
        VERTICES.forEach((V v2, Vertex<V, E> vertex2) -> {
            VERTICES.forEach((V v1, Vertex<V, E> vertex1) -> {
                VERTICES.forEach((V v3, Vertex<V, E> vertex3) -> {
                    if (v1.equals(v2) || v2.equals(v3) || v1.equals(v3)) {
                        return;
                    }

                    // v1 -> v2
                    PathInfo<V, E> path12 = getPathInfo(v1, v2, paths);
                    if (path12 == null) {
                        return;
                    }

                    // v2 -> v3
                    PathInfo<V, E> path23 = getPathInfo(v2, v3, paths);
                    if (path23 == null) {
                        return;
                    }

                    // v1 -> v3
                    PathInfo<V, E> path13 = getPathInfo(v1, v3, paths);   //1,3之前有路,且新路比13路长或者相等
                    if (path13 != null && weightWorker.compare(weightWorker.add(path12.weight, path23.weight), path13.weight) >= 0) {
                        return;
                    }
                    if (path13 == null) {
                        path13 = new PathInfo<>();
                        paths.get(v1).put(v3, path13);
                    }else {
                        path13.edgeInfos.clear();
                    }
                    path13.weight = weightWorker.add(path12.weight, path23.weight);

                    path13.edgeInfos.addAll(path12.edgeInfos);
                    path13.edgeInfos.addAll(path23.edgeInfos);
                });
            });
        });
        return paths;
    }
    private PathInfo<V, E> getPathInfo(V from, V to, Map<V, Map<V, PathInfo<V, E>>> paths) {
        Map<V, PathInfo<V, E>> map = paths.get(from);
        return map == null ? null : map.get(to);
    }




    //从paths里挑一个最短的
    private Map.Entry<Vertex<V, E>, PathInfo<V, E>> getMinPath(Map<Vertex<V, E>, PathInfo<V, E>> paths) {
        Iterator<Map.Entry<Vertex<V, E>, PathInfo<V, E>>> it = paths.entrySet().iterator();
        Map.Entry<Vertex<V, E>, PathInfo<V, E>> minEntry = it.next();
        while (it.hasNext()) {
            Map.Entry<Vertex<V, E>, PathInfo<V, E>> entry = it.next();
            if (weightWorker.compare(entry.getValue().weight, minEntry.getValue().weight) < 0) {
                minEntry = entry;
            }
        }
        return minEntry;
    }


    private static class Vertex<V, E> {
        V value;
        Set<Edge<V, E>> inEdges = new HashSet<>();
        Set<Edge<V, E>> outEdges = new HashSet<>();

        public Vertex(V value) {
            this.value = value;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            Vertex<V, E> vertex = (Vertex<V, E>) o;
            return Objects.equals(value, vertex.value);
        }

        @Override
        public int hashCode() {
            return Objects.hash(value);
        }


        @Override
        public String toString() {
            return "Vertex{" +
                    "value=" + value.toString() +
                    '}';
        }
    }

    private static class Edge<V, E> {//保存边的信息

        Vertex<V, E> from;
        Vertex<V, E> to;
        E weight;

        @Override
        public String toString() {
            return "Edge{" +
                    "from=" + from +
                    ", to=" + to +
                    ", weight=" + weight +
                    '}';
        }

        public Edge(Vertex<V, E> from, Vertex<V, E> to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public boolean equals(Object o) {

            Edge<V, E> edge = (Edge<V, E>) o;
            return Objects.equals(from, edge.from) &&
                    Objects.equals(to, edge.to);
        }

        @Override
        public int hashCode() {
            return Objects.hash(from, to);
        }

        public EdgeInfo<V, E> info() {
            return new EdgeInfo<>(from.value, to.value, weight);
        }
    }
}



package Topic03;

import java.util.Map;

public class Test {
    public static void main(String[] args) {
        demo01();
        System.out.println("=======================================");
        System.out.println("=======================================");
        demo02();

    }

    public static void demo02() {
        MGraph<String, Integer> graph = new MGraph<>(new MGraph.WeightWorker<>() {
            @Override
            public int compare(Integer w1, Integer w2) {
                return w1.compareTo(w2);
            }

            @Override
            public Integer add(Integer w1, Integer w2) {
                return w1 + w2;
            }
        });
        graph.addEdge("西安", "北京", 2553 );
        graph.addEdge("北京", "西安", 2553);
        graph.addEdge("西安", "成都", 812);
        graph.addEdge("成都", "西安", 812);
        graph.addEdge("西安", "郑州", 511);
        graph.addEdge("郑州", "西安", 511);
        graph.addEdge("成都", "广州", 2368);
        graph.addEdge("广州", "成都", 2368);
        graph.addEdge("郑州", "广州", 1579);
        graph.addEdge("广州", "郑州", 1579);
        graph.addEdge("广州", "上海", 1385);
        graph.addEdge("上海", "广州", 1385);
        graph.addEdge("徐州", "上海", 651);
        graph.addEdge("上海", "徐州", 651);
        graph.addEdge("北京", "徐州", 704);
        graph.addEdge("徐州", "北京", 704);
        graph.addEdge("北京", "郑州", 695);
        graph.addEdge("郑州", "北京", 695);
        graph.addEdge("郑州", "徐州", 349);
        graph.addEdge("徐州", "郑州", 349);

        // graph.print();
        Map<String, Graph.PathInfo<String, Integer>> map1 = graph.Dijkstra("北京");
        System.out.println("北京到各顶点距离:");
        map1.forEach((String string, Graph.PathInfo<String, Integer> pathinfo) -> {
            System.out.print(string + "->");
            System.out.println(pathinfo.toString());
        });
        System.out.println("===================================");
        Map<String, Graph.PathInfo<String, Integer>> map3 = graph.Dijkstra("成都");
        System.out.println("成都到:");
        map3.forEach((String string, Graph.PathInfo<String, Integer> pathinfo) -> {
            if(string.equals("上海")){
                System.out.print(string + "->");
                System.out.println(pathinfo.toString());
            }
        });
        System.out.println("===================================");
        Map<String, Graph.PathInfo<String, Integer>> map2 = graph.Dijkstra("上海");
        System.out.println("上海到:");
        map2.forEach((String string, Graph.PathInfo<String, Integer> pathinfo) -> {
            if(string.equals("西安")){
                System.out.print(string + "->");
                System.out.println(pathinfo.toString());
            }
        });
    }

    public static void demo01() {
        MGraph<String, Integer> graph = new MGraph<>(new MGraph.WeightWorker<Integer>() {
            @Override
            public int compare(Integer w1, Integer w2) {
                return w1.compareTo(w2);
            }

            @Override
            public Integer add(Integer w1, Integer w2) {
                return w1 + w2;
            }
        });
        graph.addEdge("a", "g", 9);
        graph.addEdge("b", "a", 20);
        graph.addEdge("b", "c", 10);
        graph.addEdge("b", "d", 30);
        graph.addEdge("g", "c", 18);
        graph.addEdge("c", "e", 5);
        graph.addEdge("e", "d", 12);
        graph.addEdge("f", "e", 8);
        graph.addEdge("f", "g", 10);
        graph.addEdge("e", "g", 15);

        //   graph.print();
        Map<String, Graph.PathInfo<String, Integer>> map3 = graph.Dijkstra("a");
        System.out.println("a到各顶点距离:");
        map3.forEach((String string, Graph.PathInfo<String, Integer> pathinfo) -> {
            System.out.print(string + "->");
            System.out.println(pathinfo.toString());
        });
        System.out.println("==================");
        Map<String, Map<String, Graph.PathInfo<String, Integer>>> map = graph.Floyd();
        map.forEach((String string, Map<String, Graph.PathInfo<String, Integer>> map2) -> {
            Map<String, Graph.PathInfo<String, Integer>> map4 = map2;
            System.out.println(string+"到各顶点距离:");
            map4.forEach((String string2, Graph.PathInfo<String, Integer> pathinfo) -> {
                System.out.print(string2 + "->");
                System.out.println(pathinfo.toString());
            });
        });
    }
}


3.4实例测试及运行结果
运行示例一

在这里插入图片描述
在这里插入图片描述

运行示例二

在这里插入图片描述
在这里插入图片描述

3.5实验心得

用Graph接口标明主要api,并且在里面申明内部类PathInfo<V, E>以便保存迪杰斯特拉算法和弗洛伊德算法的返回值.

用内部类且声明为private就能保障程序封装性.

我在MGraph中声明了一个接口,用于比较权值并进行权值的求和,在声明MGraph的地方使用匿名内部类,对接口中的方法进行重写.

五.学生管理系统

此题有误,我把内容以string存储了,但是向文件里存储时存储了地址,可以把string类型的内容改成char数组

5.1问题描述

随着大学规模的不断扩大,有关各种学生信息的数据量也不断增大。学生有本科生、研究生和助教博士生,校方需要对这些学生的信息进行计算机管理。所开发的软件应包括各类学生的添加、修改、删除和查找等功能。考虑到软件的可重用性、可扩展性和可维护性,校方决定采用面向对象的程序设计方法来开发系统。学生信息需要以文件方式保存到计算机硬盘中。另外,系统的用户界面应该尽可能友好,方便用户使用。

5.2设计需求及分析

(1) 使用C++语言开发,充分利用面向对象程序设计的类、对象、继承、封装和多态性等

概念来设计和实现该管理系统。

(2) 设计一个Person(人员)类,考虑到通用性,只抽象出所有类型人员都具有的属性:name(姓名), id(身份证号),gender(性别),birthday(出生日期)等等。其中“出生日期”为内嵌子对象,是一个Date(日期)类型,Date类具有属性: year(年),month(月),day(日)。用成员函数实现对人员信息的录入和显示等必要功能操作。

(3) 从Person类派生出Student(学生)类,添加属性: studentNo(学号),schoolName(学校),classIn (班级)。从Person类派生出Teacher(教师)类,添加属性:teacherNo(教师编号),schoolName(学校),department(部门)。

(4) 从Student类中派生出UnderGraduate(本科生)类,添加属性:major(专业)。从Student类中派生出Graduate(研究生)类,添加属性:direction(研究方向),adviserName(导师姓名)。

(5) 从Graduate类和Teacher类派生出TA(助教博士生)类。

(6) 写程序测试上述各类,看能否正常运行。

(7) 构建必要的辅助类,实现对本科生、研究生和助教博士生的添加、修改、删除、查询管理。

(8) 根据需要定义类的构造函数、析构函数、拷贝构造函数、成员函数。必要时重载函数。

(9) 要求将Person类设置为虚基类,以消除其派生类成员访问的二义性问题(注意在虚基类各级派生类的构造函数实现时调用虚基类的构造函数)。

(10) 要求在Person类中定义虚函数displayDetails(),用于显示当前对象的信息;同时定义虚函数inputData( ),用于从键盘获取当前对象的信息。Person类所有派生类也要定义同名虚函数,使程序可以实现动态多态性。

(11) 用菜单方式设计主控模块程序。

(12) 对程序源代码要给出各部分的详细注释,这也是该题目的考核重点之一。

(13) 用UML语言描述系统用到的类及其关系。

5.3设计功能的实现
#include <iostream>

using namespace std;
#include "UnderGraduateManager.h"
#include "GraduateManager.h"

#include "TAManager.h"
int main() {

    int choice;
    UnderGraduateManager underGraduateManager;
 GraduateManager graduateManager;
    TAManager taManager;
    cout<<endl;
    cout<<"Student System"<<endl;
    cout<<"1.undergraduate 2.graduate 3.TA 4.exit"<<endl;
    cin>>choice;
    while(choice!=4){
        if(choice==1){
           underGraduateManager.dataManager();
        }else if(choice==2){
        graduateManager.dataManager();

        }else if(choice==3){
            taManager.dataManager();
        }

        cout<<"1.undergraduate 2.graduate 3.TA 4.exit"<<endl;
        cin>>choice;
    }
    cout<<"exit"<<endl;
    return  0;
}

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_DATE_H
#define SSC_DATE_H

#include <iostream>

using namespace std;

class Date {
private:
    int year;
    int month;
    int day;
public:
    Date(int year, int month, int day) : year(year), month(month), day(day) {}
    Date(){
        year=0;
        month=0;
        day=0;
    }
    Date(Date&d){
        year=d.year;
        month=d.month;
        day=d.day;
    }

    virtual ~Date() {
    }
    void inputDate(){
        cout<<"year:";
        cin>>year;
        cout<<"month:";
        cin>>month;
        cout<<"day:";
        cin>>day;
    }

    friend ostream &operator<<(ostream &os, const Date &date) {
        os << "year: " << date.year << " month: " << date.month << " day: " << date.day;
        return os;
    }
};

#endif //SSC_DATE_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_PERSON_H
#define SSC_PERSON_H

#include <iostream>

using namespace std;

#include "Date.h"

class Person {
protected:
    string name;
    string id;
    string gender;
    Date birthday;
public:
    Person() {}

    Person(const string &name, const string &id, const string &gender, int year, int month, int day) : name(name),
                                                                                                       id(id),
                                                                                                       gender(gender),
                                                                                                       birthday(year,
                                                                                                                month,
                                                                                                                day) {}

  virtual  void inputData() {
        cout << "name:";
        cin >> name;
        cout << "id:";
        cin >> id;
        cout << "gender:";
        cin >> gender;
        cout << "birthday:";
        birthday.inputDate();
    }

    friend ostream &operator<<(ostream &os, const Person &person) {
        os << "name: " << person.name << " id: " << person.id << " gender: " << person.gender << " birthday: "
           << person.birthday;
        return os;
    }

    const string &getName() const {
        return name;
    }

    void setName(const string &name) {
        Person::name = name;
    }

    const string &getId() const {
        return id;
    }

    void setId(const string &id) {
        Person::id = id;
    }

    const string &getGender() const {
        return gender;
    }

    void setGender(const string &gender) {
        Person::gender = gender;
    }

    const Date &getBirthday() const {
        return birthday;
    }

    void setBirthday(const Date &birthday) {
        Person::birthday = birthday;
    }
};


#endif //SSC_PERSON_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_STUDENT_H
#define SSC_STUDENT_H

#include <iostream>
#include "Person.h"
using namespace std;
class Student :virtual public Person{
protected:
    string  studentNo;
    string schoolName;
    string classIn;
public:
    Student() {}

    Student(const string &name, const string &id, const string &gender, int year, int month, int day,
            const string &studentNo, const string &schoolName, const string &classIn) : Person(name, id, gender, year,
                                                                                               month, day),
                                                                                        studentNo(studentNo),
                                                                                        schoolName(schoolName),
                                                                                        classIn(classIn) {}

    virtual ~Student() {

    }
    void inputDate(){
        Person::inputData();
        cout<<"studentNo:";
        cin>>studentNo;
        cout<<"schoolName:";
        cin>>schoolName;
        cout<<"classIn:";
        cin>>classIn;
    }

    friend ostream &operator<<(ostream &os, const Student &student) {
        os << static_cast<const Person &>(student) << " studentNo: " << student.studentNo << " schoolName: "
           << student.schoolName << " classIn: " << student.classIn;
        return os;

    }

    const string &getStudentNo() const {
        return studentNo;
    }

    void setStudentNo(const string &studentNo) {
        Student::studentNo = studentNo;
    }

    const string &getSchoolName() const {
        return schoolName;
    }

    void setSchoolName(const string &schoolName) {
        Student::schoolName = schoolName;
    }

    const string &getClassIn() const {
        return classIn;
    }

    void setClassIn(const string &classIn) {
        Student::classIn = classIn;
    }
};


#endif //SSC_STUDENT_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_TEACHER_H
#define SSC_TEACHER_H
#include <iostream>
#include "Person.h"
using namespace std;
class Teacher:virtual public Person{
protected:
    string teacherNo;
    string schoolName;
    string department;
public:
    Teacher()  {}

    virtual ~Teacher() {

    }

    Teacher(const string &name, const string &id, const string &gender, int year, int month, int day,
            const string &teacherNo, const string &schoolName, const string &department) : Person(name, id, gender,
                                                                                                  year, month, day),
                                                                                           teacherNo(teacherNo),
                                                                                           schoolName(schoolName),
                                                                                           department(department) {}

    void inputData(){
        Person::inputData();
        cout<<"teacherNo:";
        cin>>teacherNo;
        cout<<"schoolName:";
        cin>>schoolName;
        cout<<"department:";
        cin>>department;
    }

    friend ostream &operator<<(ostream &os, const Teacher &teacher) {
        os << static_cast<const Person &>(teacher) << " teacherNo: " << teacher.teacherNo << " schoolName: "
           << teacher.schoolName << " department: " << teacher.department;
        return os;
    }

    const string &getTeacherNo() const {
        return teacherNo;
    }

    void setTeacherNo(const string &teacherNo) {
        Teacher::teacherNo = teacherNo;
    }

    const string &getSchoolName() const {
        return schoolName;
    }

    void setSchoolName(const string &schoolName) {
        Teacher::schoolName = schoolName;
    }

    const string &getDepartment() const {
        return department;
    }

    void setDepartment(const string &department) {
        Teacher::department = department;
    }
};

#endif //SSC_TEACHER_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_GRADUATE_H
#define SSC_GRADUATE_H
#include <iostream>
#include "Student.h"
using namespace std;

class Graduate:virtual public Student{
protected:
    string direction;
    string adviserName;
public:
    Graduate() {}

    Graduate(const string &name, const string &id, const string &gender, int year, int month, int day,
             const string &studentNo, const string &schoolName, const string &classIn, const string &direction,
             const string &adviserName) : Student(name, id, gender, year, month, day, studentNo, schoolName, classIn),
                                          direction(direction), adviserName(adviserName) {}

    virtual ~Graduate() {

    }

    const string &getDirection() const {
        return direction;
    }

    void setDirection(const string &direction) {
        Graduate::direction = direction;
    }

    const string &getAdviserName() const {
        return adviserName;
    }

    void setAdviserName(const string &adviserName) {
        Graduate::adviserName = adviserName;
    }
    void inputData(){
        Student::inputDate();
        cout<<"direction:";
        cin>>direction;
        cout<<"adviserName:";
        cin>>adviserName;

    }

    friend ostream &operator<<(ostream &os, const Graduate &graduate) {
        os << static_cast<const Student &>(graduate) << " direction: " << graduate.direction << " adviserName: "
           << graduate.adviserName;
        return os;
    }
};


#endif //SSC_GRADUATE_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_GraduateMANAGER_H
#define SSC_GraduateMANAGER_H

#include "Graduate.h"
#include <iostream>

using namespace std;

#include <fstream>

class GraduateManager {
protected:
    int top;
    Graduate temp1[100];

    void displayAll() {
        if(top==-1){
            cout<<"nothing"<<endl;
        }
        for (int i = 0; i <= top; i++) {
            cout << temp1[i] << endl;
        }
    }

    void removeAll() {
        top = -1;
        dataSave();
        cout << "Finish emptying" << endl;
    }

    int searchByNo(string no) {
        for (int i = 0; i <= top; i++) {
            if (temp1[i].getStudentNo() == no) {
                return i;
            }

        }
        return -1;
    }

    void dataSave() {
        fstream file("Graduate.dat", ios::out);
        for (int i = 0; i <= top; i++) {
            file.write((char *) &temp1[i], sizeof(100));
        }
        file.close();
    }

    void addStudent(Graduate undergraduate2) {
        int flag = searchByNo(undergraduate2.getStudentNo());
        if (flag != -1) {
            cout << "Student already exists" << endl;
            return;
        } else {
            top++;
            temp1[top] = undergraduate2;
            dataSave();

        }
    }

    void revise(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "Student does not exist" << endl;
            return;
        } else {
            cout << "Enter the student's information:" << endl;
            temp1[position].inputData();
            dataSave();
        }
    }

    void remove(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "This student number does not exist" << endl;
            return;
        } else {
            for (int i = position; i < top; i++) {
                temp1[i] = temp1[i + 1];
            }
            top--;
            cout << "successfully deleted" << endl;
            dataSave();

        }
    }

    void findstudent(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "This student number does not exist" << endl;
            return;
        } else {
            cout << temp1[position];
            dataSave();
        }
    }

public:
    virtual ~GraduateManager() {
        dataSave();
    }

    GraduateManager() {
        Graduate s;
        top = -1;
        fstream file("Graduate.dat", ios::in);
        while (true) {
            file.read((char *) &s, sizeof(100));
            if (!file)
                break;

            temp1[++top] = s;
        }
        file.close();
    }

    void dataManager() {
        int choice = 1;

        Graduate underGraduate1;
        while (choice != 0) {
            cout << "\nGradute manage" << endl;
            cout << "1.add\n2.revise\n3.remove\n4.find\n5.display\n6.remove all\n0.exit" << endl;
            cin >> choice;
            string s;
            switch (choice) {
                case 1:
                    underGraduate1.inputData();
                    addStudent(underGraduate1);
                    break;
                case 2:
                    cout << "Enter student number:";
                    cin >> s;
                    revise(s);
                    break;
                case 3:
                    cout << "Enter student number:";
                    cin >> s;
                    remove(s);
                    break;
                case 4:
                    cout << "Enter student number:";
                    cin >> s;
                    findstudent(s);
                    break;
                case 5:
                    displayAll();
                    break;
                case 6:
                    removeAll();
                    break;
                default:
                    break;
            }
        }
    }


};


#endif //SSC_GraduateMANAGER_H
//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_TA_H
#define SSC_TA_H
#include <iostream>
#include "Graduate.h"
#include "Teacher.h"

class TA:public Teacher , public Graduate {
public:
    TA( const string &name, const string &id, const string &gender, int year, int month,
       int day, const string &teacherNo, const string &schoolName, const string &department, const string &studentNo,
       const string &classIn, const string &direction, const string &adviserName) : Teacher() {

    }

    TA()  {}

    virtual ~TA() {

    }

    void inputData() override {
        Graduate::inputData();
        cout<<"teacherNo:";
        cin>>teacherNo;
        cout<<"department:";
        cin>>department;
    }

    friend ostream &operator<<(ostream &os, const TA &ta) {
        os <<static_cast<const Graduate &>(ta) << ' ' <<"teacherNo:"<<ta.getTeacherNo()<< ' '<<"department:"<<ta.getDepartment();
        return os;
    }
};


#endif //SSC_TA_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_TAMANAGER_H
#define SSC_TAMANAGER_H

#include "TA.h"
#include <iostream>

using namespace std;

#include <fstream>

class TAManager {
protected:
    int top;
    TA temp1[100];

    void displayAll() {
        if(top==-1){
            cout<<"nothing"<<endl;
        }
        for (int i = 0; i <= top; i++) {
            cout << temp1[i] << endl;
        }
    }

    void removeAll() {
        top = -1;
        dataSave();
        cout << "Finish emptying" << endl;
    }

    int searchByNo(string no) {
        for (int i = 0; i <= top; i++) {
            if (temp1[i].getStudentNo() == no) {
                return i;
            }

        }
        return -1;
    }

    void dataSave() {
        fstream file("TA.dat", ios::out);
        for (int i = 0; i <= top; i++) {
            file.write((char *) &temp1[i], sizeof(150));
        }
        file.close();
    }

    void addStudent(TA undergraduate2) {
        int flag = searchByNo(undergraduate2.getStudentNo());
        if (flag != -1) {
            cout << "Student already exists" << endl;
            return;
        } else {
            top++;
            temp1[top] = undergraduate2;
            dataSave();

        }
    }

    void revise(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "Student does not exist" << endl;
            return;
        } else {
            cout << "Enter the student's information:" << endl;
            temp1[position].inputData();
            dataSave();
        }
    }

    void remove(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "This student number does not exist" << endl;
            return;
        } else {
            for (int i = position; i < top; i++) {
                temp1[i] = temp1[i + 1];
            }
            top--;
            cout << "successfully deleted" << endl;
            dataSave();

        }
    }

    void findstudent(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "This student number does not exist" << endl;
            return;
        } else {
            cout << temp1[position];
            dataSave();
        }
    }

public:
    virtual ~TAManager() {
        dataSave();
    }

    TAManager() {
        TA s;
        top = -1;
        fstream file("TA.dat", ios::in);
        while (true) {

            file.read((char *) &s, sizeof(100));
            if (!file)
                break;

            temp1[++top] = s;
        }
        file.close();
    }

    void dataManager() {
        int choice = 1;

        TA underGraduate1;
        while (choice != 0) {
            cout << "\nTA manage" << endl;
            cout << "1.add\n2.revise\n3.remove\n4.find\n5.display\n6.remove all\n0.exit" << endl;
            cin >> choice;
            string s;
            switch (choice) {
                case 1:
                    underGraduate1.inputData();
                    addStudent(underGraduate1);
                    break;
                case 2:
                    cout << "Enter student number:";
                    cin >> s;
                    revise(s);
                    break;
                case 3:
                    cout << "Enter student number:";
                    cin >> s;
                    remove(s);
                    break;
                case 4:
                    cout << "Enter student number:";
                    cin >> s;
                    findstudent(s);
                    break;
                case 5:
                    displayAll();
                    break;
                case 6:
                    removeAll();
                    break;
                default:
                    break;
            }
        }
    }


};


#endif //SSC_TAMANAGER_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_UNDERGRADUATE_H
#define SSC_UNDERGRADUATE_H
#include <iostream>
#include "Student.h"
using namespace std;
class UnderGraduate:virtual  public Student{
protected:
    string major;
public:
    UnderGraduate() {}

    virtual ~UnderGraduate() {

    }

    UnderGraduate(const string &name, const string &id, const string &gender, int year, int month, int day,
                  const string &studentNo, const string &schoolName, const string &classIn, const string &major)
            : Student(name, id, gender, year, month, day, studentNo, schoolName, classIn), major(major) {}
    void inputData(){
        Student::inputDate();
        cout<<"major";
        cin>>major;
    }

    friend ostream &operator<<(ostream &os, const UnderGraduate &graduate) {
        os << static_cast<const Student &>(graduate) << " major: " << graduate.major;
        return os;
    }

    const string &getMajor() const {
        return major;
    }

    void setMajor(const string &major) {
        UnderGraduate::major = major;
    }
};
#endif //SSC_UNDERGRADUATE_H

//
// Created by lalall on 2020/6/19.
//

#ifndef SSC_UNDERGRADUATEMANAGER_H
#define SSC_UNDERGRADUATEMANAGER_H

#include "UnderGraduate.h"
#include <iostream>

using namespace std;

#include <fstream>

class UnderGraduateManager {
protected:
    int top;
    UnderGraduate temp1[100];

    void displayAll() {
        if(top==-1){
            cout<<"nothing"<<endl;
        }
        for (int i = 0; i <= top; i++) {
            cout << temp1[i] << endl;
        }
    }

    void removeAll() {
        top = -1;
        dataSave();
        cout << "Finish emptying" << endl;
    }

    int searchByNo(string no) {
        for (int i = 0; i <= top; i++) {
            if (temp1[i].getStudentNo() == no) {
                return i;
            }

        }
        return -1;
    }

    void dataSave() {
        fstream file("Undergraduate.dat", ios::out);
        for (int i = 0; i <= top; i++) {
            file.write((char *) &temp1[i], sizeof(150));
        }
        file.close();
    }

    void addStudent(UnderGraduate undergraduate2) {
        int flag = searchByNo(undergraduate2.getStudentNo());
        if (flag != -1) {
            cout << "Student already exists" << endl;
            return;
        } else {
            top++;
            temp1[top] = undergraduate2;
            dataSave();

        }
    }

    void revise(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "Student does not exist" << endl;
            return;
        } else {
            cout << "Enter the student's information:" << endl;
            temp1[position].inputData();
            dataSave();
        }
    }

    void remove(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "This student number does not exist" << endl;
            return;
        } else {
            for (int i = position; i < top; i++) {
                temp1[i] = temp1[i + 1];
            }
            top--;
            cout << "successfully deleted" << endl;
            dataSave();

        }
    }

    void findstudent(string s) {
        int position = searchByNo(s);
        if (position == -1) {
            cout << "This student number does not exist" << endl;
            return;
        } else {
            cout << temp1[position];
            dataSave();
        }
    }

public:
    virtual ~UnderGraduateManager() {
        dataSave();
    }

    UnderGraduateManager() {
        UnderGraduate s;
        top = -1;
        fstream file("Undergraduate.dat", ios::in);
        while (true) {

            file.read((char *) &s, sizeof(150));
            if (!file)
                break;

            temp1[++top] = s;
        }
        file.close();
    }

    void dataManager() {
        int choice = 1;

        UnderGraduate underGraduate1;
        while (choice != 0) {
            cout << "undergradute manage" << endl;
            cout << "1.add\n2.revise\n3.remove\n4.find\n5.display\n6.remove all\n0.exit" << endl;
            cin >> choice;
            string s;
            switch (choice) {
                case 1:
                    underGraduate1.inputData();
                    addStudent(underGraduate1);
                    break;
                case 2:
                    cout << "Enter student number:";
                    cin >> s;
                    revise(s);
                    break;
                case 3:
                    cout << "Enter student number:";
                    cin >> s;
                    remove(s);
                    break;
                case 4:
                    cout << "Enter student number:";
                    cin >> s;
                    findstudent(s);
                    break;
                case 5:
                    displayAll();
                    break;
                case 6:
                    removeAll();
                    break;
                default:
                    break;
            }
        }
    }


};


#endif //SSC_UNDERGRADUATEMANAGER_H

5.4实例测试及运行结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5.5实验心得

设计了三个XXManager类来管理三类学生,实现向文件中读写信息,要注意virtual的使用,合理使用虚函数和虚继承,使类的功能更强大,使程序的可读性更强.

在写程序时要注重安全性,不要总是用public修饰

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值