C++day8作业

封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)

再把该容器中的对象,保存到文件中。

再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。

cpp 复制代码
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;


class Stu
{
private:
    string name;
    int age;
    int id;
public:
    Stu(){}
    Stu(string name,int age,int id):name(name),age(age),id(id){}
    string wri()const
    {
        return name + " " + to_string(age) + " " + to_string(id);
    }
};
int main()
{
    vector<Stu> stus;
    stus.push_back(Stu("张三",20,1001));
    stus.push_back(Stu("李四",21,1002));
    stus.push_back(Stu("王五",20,1003));
    ofstream ofs;
    try {
        ofs.open("D:/QT/QT/day8/aaa",ios::out);
        if(!ofs.is_open())
        {
            throw -1;
        }
    } catch (int &e) {
        if(e==-1)
        {
            cout << "打开失败" << endl;
        }
    }

    for(auto &stu : stus)
    {
        ofs << stu.wri() <<endl;
    }
    ofs.close();

    ifstream ifs;
    try {
        ifs.open("D:/QT/QT/day8/aaa",ios::in);
        if(!ifs.is_open())
        {
            throw -1;
        }
    } catch (int &c) {
        if(c==-1)
        {
            cout << "打开失败" << endl;
        }
    }

    char buf[1024];
    while(ifs>>buf)
    {
        cout << buf << endl;
    }

    ifs.close();
    return 0;
}

实现list的相关函数

cpp 复制代码
#include <iostream>
#include <list>
using namespace std;

void printfList(list<int> &lst)
{
    list<int>::iterator iter;
    for(iter = lst.begin(); iter != lst.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;
}

int main()
{
    list<int> lst;
    lst.push_back(10);
    lst.push_back(20);
    lst.push_back(30);
    lst.push_back(40);
    lst.push_back(50);

    printfList(lst);

    list<int>  lst1;
    lst1=lst;
    printfList(lst1);
    list<int>  lst2(lst1);
    printfList(lst2);
    list<int> lst3;
    lst3.assign(lst2.begin(),lst2.end());
    printfList(lst3);

    if(!lst.empty())
    {
        cout << "aaa" <<endl;
        cout << lst.size() << endl;
    }
    cout << "===============" <<endl;
    lst.resize(6,5);
    printfList(lst);
    cout << "===============" <<endl;
    printfList(lst1);
    lst1.pop_back();
    printfList(lst1);
    cout << "===============" <<endl;
    printfList(lst2);
    lst2.insert(lst2.begin(),90);
    printfList(lst2);
    cout << "===============" <<endl;
    printfList(lst3);
    lst3.clear();
    printfList(lst3);
    return 0;
}

思维导图

相关推荐
努力学习的小廉33 分钟前
我爱学算法之—— 分治-归并
c++·算法·1024程序员节
九皇叔叔36 分钟前
Java循环结构全解析:从基础用法到性能优化
java·开发语言·性能优化
仰泳的熊猫43 分钟前
LeetCode:200. 岛屿数量
数据结构·c++·算法·leetcode
sulikey44 分钟前
Qt 入门简洁笔记:从框架概念到开发环境搭建
开发语言·前端·c++·qt·前端框架·visual studio·qt框架
zzzsde1 小时前
【C++】stack和queue:优先级队列的使用及底层原理
开发语言·c++
让我们一起加油好吗1 小时前
【数论】费马小定理
c++·算法·数论·1024程序员节·费马小定理·逆元
是苏浙1 小时前
零基础入门C语言之操作符详解2
c语言·开发语言
m0_748233642 小时前
单调队列【C/C++】
c语言·c++·算法·1024程序员节
总有刁民想爱朕ha2 小时前
银河麒麟v10批量部署Python Flask项目小白教程
开发语言·python·flask·银河麒麟v10
yi碗汤园2 小时前
【一文了解】八大排序-插入排序、希尔排序
开发语言·算法·unity·c#·1024程序员节