vector存放自定义数据类型(3)
学习目标:
vector存放自定义数据类型,并打印输出
解引用:
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 using namespace std; 5 6 //vector存放自定义数据类型 7 class Person 8 { 9 public: 10 11 Person(string name, int age) 12 { 13 this->m_Name = name; 14 this->m_Age = age; 15 } 16 17 string m_Name; 18 int m_Age; 19 }; 20 21 void test_01(void) 22 { 23 vector<Person> v;//创建对象 24 Person p1("aaa", 10); 25 Person p2("bbb", 20); 26 Person p3("ccc", 30); 27 Person p4("ddd", 40); 28 29 //向容器种添加数据 30 v.push_back(p1); 31 v.push_back(p2); 32 v.push_back(p3); 33 v.push_back(p4); 34 35 //遍历容器中的数据 36 for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) 37 { 38 //对于 类 类型数据的访问方式 39 cout << "姓名:" << (*it).m_Name << "年龄:" << (*it).m_Age << endl;//解引用之后成为Person的对象 40 cout << "姓名:" << it->m_Name << "年龄:" << it->m_Age << endl;//it为Person类指针 41 } 42 } 43 44 //存放自定义数据类型 指针 45 void test_02(void) 46 { 47 vector<Person*> v;//创建对象 48 Person p1("aaa", 10); 49 Person p2("bbb", 20); 50 Person p3("ccc", 30); 51 Person p4("ddd", 40); 52 53 //向容器种添加数据 54 v.push_back(&p1); 55 v.push_back(&p2); 56 v.push_back(&p3); 57 v.push_back(&p4); 58 59 //遍历指针数组 60 for (vector<Person*>::iterator it = v.begin(); it != v.end(); it++) 61 { 62 //it解引用之后就是Person类的对象 63 cout << "姓名:" << (*it)->m_Name << " 年龄:" << (*it)->m_Age << endl; 64 } 65 66 } 67 68 int main(void) 69 { 70 //test_01(); 71 test_02(); 72 73 system("pause"); 74 return 0; 75 }