qfedu-cpp-level/day8/stl_code/d2.cpp

47 lines
881 B
C++

// 存放类对象的数据 vector
#include <bits/stdc++.h>
using namespace std;
class Student
{
friend ostream &operator<<(ostream &out, const Student &stu);
private:
string name;
int age;
public:
Student(const string &name, int age)
{
this->name = name;
this->age = age;
}
};
ostream &operator<<(ostream &out, const Student &stu)
{
out << "name: " << stu.name << ", age: " << stu.age;
return out;
}
int main()
{
vector<Student> v;
v.push_back(Student("zhangsan", 20));
v.push_back(Student("lisi", 21));
v.push_back(Student("wangwu", 22));
v.push_back(Student("zhaoliu", 23));
v.pop_back(); // 删除最后一个元素
// 创建迭代器
vector<Student>::iterator it = v.end();
while (it != v.begin())
{
cout << *(--it) << endl; // 重载了<<运算符
}
return 0;
}