#include<iostream>
using namespace std;
#include<vector>
#include<string>
class Person
{
public:
Person(int age, string name)
{
this->age = age;
this->name = name;
}
int age;
string name;
};
void test01()
{
vector<Person> v;
Person p1(11, "tom");
Person p2(11, "tom");
Person p3(11, "tom");
Person p4(11, "tom");
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
//指针的方式输出
cout << "年龄" << it->age << " " << "姓名" << it->name << endl;
//解引用输出
cout << "年龄" << (*it).age << " " << "姓名" << (*it).name << endl;
}
}
void test02()
{
vector<Person *> v;
Person p1(11, "tom");
Person p2(11, "tom");
Person p3(11, "tom");
Person p4(11, "tom");
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
for (vector<Person *>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "年龄" << (*it)->age << " " << "姓名" << (*it)->name << endl;
cout << "年龄" << (**it).age << " " << "姓名" << (**it).name << endl;
}
}
int main()
{
test01();
test02();
return 0;
}
vector存放自定义数据类型(类和指针)
最新推荐文章于 2024-07-10 22:49:54 发布