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

思维导图

相关推荐
樱木Plus10 小时前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit2 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_3 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星3 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛5 天前
delete又未完全delete
c++
端平入洛6 天前
auto有时不auto
c++
郑州光合科技余经理7 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1237 天前
matlab画图工具
开发语言·matlab
dustcell.7 天前
haproxy七层代理
java·开发语言·前端
norlan_jame7 天前
C-PHY与D-PHY差异
c语言·开发语言