C++day7模板、异常、auto关键字、lambda表达式、数据类型转换、STL、list、文件操作

作业

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

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

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

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

class Stu
{
    friend ifstream & operator>>(ifstream &cin,Stu &s);
    friend ofstream & operator<<(ofstream &cout,Stu &s);
    friend ostream & operator<<(ostream &cout,Stu &s);
private:
    string name;
    int age;
public:
    Stu(){}
    Stu(string n,int a):name(n),age(a)
    {}
};

ostream & operator<<(ostream &cout,Stu &s)
{
    cout << s.name;
    cout << s.age << endl;
    return cout;
}
ofstream & operator<<(ofstream &cout,Stu &s)
{
    cout << s.name << "\t" << s.age << endl;
    return cout;
}
ifstream & operator>>(ifstream &cin,Stu &s)
{
    cin >> s.name;
    cin >> s.age;
    return cin;
}
int main()
{
//    ofstream ofs;
//    ofs.open("E:/CFHD/1.txt",ios::out);
//    vector<Stu> v;
//    Stu a("zhangsan",18);
//    Stu b("lisi",20);
//    Stu c("wangwu",22);
//    v.push_back(a);
//    v.push_back(b);
//    v.push_back(c);
//    for(int i = 0;i<3;i++)
//    {
//        ofs << v.at(i);
//    }
//    ofs.close();
    ifstream ifs;
    ifs.open("E:/CFHD/1.txt",ios::in);
    vector<Stu> v;
    vector<Stu>::iterator iter;
    Stu s;
    int i = 0;
    while(ifs >> s)
    {
        iter = v.begin()+i;
        v.push_back(s);
        i++;
    }
    for(iter = v.begin();iter != v.end();iter++)
    {
        cout << *iter ;
    }
    ifs.close();

    return 0;
}

把list的相关函数都实现出来

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

void P(list<int> &l)
{
    list<int>::iterator iter;
    for(iter = l.begin();iter != l.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;
}
int main()
{
    list<int> lst1;
    for(int i = 0;i<5;i++)
    {
        lst1.push_back(i);
    }
    P(lst1);
    list<int> lst2(lst1.begin(),lst1.end());
    P(lst2);
    list<int> lst3(3,8);
    P(lst3);
    list<int> lst4;
    lst4.assign(lst1.begin(),lst1.end());
    P(lst4);
    cout<<"front = "<<lst2.front()<<endl;
    cout<<"back = "<<lst2.back()<<endl;
    if(!lst1.empty())
    {
        cout << "sz= " << lst1.size() << endl;
        lst1.resize(15,2);
        cout << "sz= " << lst1.size() << endl;
        P(lst1);
    }
    lst1.erase(lst1.begin(),lst1.end());
    P(lst1);
    cout << "sz= " << lst1.size() << endl;

    return 0;
}

思维导图

相关推荐
yeziyfx21 小时前
kotlin中 ?:的用法
android·开发语言·kotlin
charlie11451419121 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
古城小栈21 小时前
Rust 网络请求库:reqwest
开发语言·网络·rust
hqwest1 天前
码上通QT实战12--监控页面04-绘制6个灯珠及开关
开发语言·qt·qpainter·qt事件·stackedwidget
i橡皮擦1 天前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
bing.shao1 天前
golang 做AI任务执行
开发语言·人工智能·golang
源代码•宸1 天前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
basketball6161 天前
python 的对象序列化
开发语言·python
fie88891 天前
钢结构件制造车间生产调度实例:MATLAB实现(基于遗传算法)
开发语言·matlab·制造
沐知全栈开发1 天前
PHP 安装指南
开发语言