#include<iostream>
using namespace std;
#include<vector>
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
void test01()
{
vector<Person>v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
//向容器中添加数据
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
//遍历容器中的数据
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
//cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << endl;
cout << "姓名:" << it->m_Name << " 年龄:" << it->m_Age << endl;
}
}
//存放自定义数据类型 指针
void test02()
{
vector<Person*>v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
//向容器中添加数据
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
//遍历容器
for (vector<Person*>::iterator it = v.begin(); it != v.end(); it++)
{
//cout << "姓名:" << (*(*it)).m_Name << " 年龄:" << (*(*it)).m_Age << endl;
cout << "姓名:" << (*it)->m_Name << " 年龄:" << (*it)->m_Age << endl;
}
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
c++学习记录 STL初识—vector存放自定义数据类型
最新推荐文章于 2024-10-31 18:26:46 发布
本文介绍了如何在C++中创建Person类,使用vector容器存储对象实例和指针,并展示了test01和test02函数分别处理这两种情况的遍历方法。
摘要由CSDN通过智能技术生成