C++标准模板库练习

1.

#include <iostream>
#include<list>
using namespace std;

void printList(list<int> &lst)
{
     list<int>::iterator iter;
     iter = lst.begin();
     lst.insert(iter,55);
     for(iter = lst.begin(); iter != lst.end(); iter++)
     {
         cout << *iter << " ";
     }
     cout << endl;
}
int main()
{
    list<int> lst;
    lst.push_back(11);
    lst.push_back(22);
    lst.push_back(33);
    lst.push_back(44);

    lst.insert(lst.begin(),66);
    printList(lst);

    list<int> lst1(lst);
    printList(lst1);

    list<int> lst2 = lst;
    lst2.insert(lst2.begin(),99);
    printList(lst2);



    if(lst2.empty())
    {
        cout << "容器为空" << endl;
    }
    else
    {

        cout << "元素个数" << lst2.size() << endl;

        lst2.resize(10);
        printList(lst2);
    }
    return 0;
}
#include <iostream>
#include<fstream>
#include<vector>
using namespace std;

class Stu
{
    string name;
public:
    Stu(){}
    Stu(string s):name(s)
    {}
//    string getName()
//    {
//         return name;
//    }
    friend ostream& operator<<(ostream& os, const Stu& stu);
    friend istream& operator>>(istream& cin,Stu& Stu);
};
ostream& operator<<(ostream& os, const Stu& stu)
{
     os << stu.name;
     return os;
}

istream& operator>>(istream& cin, Stu& Stu)
{
     cin >> Stu.name;
     return cin;
}

void printVector(vector<Stu> &v)
{
    vector<Stu>::iterator iter;
    for(iter = v.begin(); iter != v.end(); iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;
}
int main()
{

    //容器
    vector<Stu> v;//无参构造函数
    vector<Stu> v2;
    v.push_back(Stu("zhangsan"));
    v.push_back(Stu("lisi"));
    v.push_back(Stu("wangwu"));
    vector<Stu>::iterator iter;

   ofstream ofs;
   ofs.open("D:/qt5.14/c/stu.txt",ios::out);// 会清空
   for(iter=v.begin();iter!=v.end();iter++)
   {
       ofs << *iter << endl;
   }
   ofs.close();

   ifstream ifs;
   ifs.open("D:/qt5.14/c/stu.txt",ios::in);
   Stu s1;
   while(ifs>>s1)
   {
       v2.push_back(s1);
   }
   printVector(v2);
   ifs.close();


    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值