1.文章来源:https://www.toymoban.com/news/detail-682673.html
#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;
}
文章来源地址https://www.toymoban.com/news/detail-682673.html
到了这里,关于C++标准模板库练习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!