C++//vector存放自定义数据类型
1 //vector存放自定义数据类型 2 3 #include <iostream> 4 #include <string> 5 #include<fstream> 6 #include<vector> 7 #include<algorithm> 8 using namespace std; 9 10 11 class Person 12 { 13 public: 14 Person(string name, int age) 15 { 16 this->m_Name = name; 17 this->m_Age = age; 18 } 19 20 string m_Name; 21 int m_Age; 22 }; 23 24 void test01() 25 { 26 vector<Person>v; 27 28 Person p1("张三", 10); 29 Person p2("李四", 80); 30 Person p3("王五", 40); 31 Person p4("赵六", 30); 32 Person p5("孙七", 30); 33 34 //向容器长添加数据 35 36 v.push_back(p1); 37 v.push_back(p2); 38 v.push_back(p3); 39 v.push_back(p4); 40 v.push_back(p5); 41 42 //遍历容器中的数据 43 for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) 44 { 45 46 //cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << endl; 47 cout << "姓名:" << it->m_Name << " 年龄:" << it->m_Age << endl; 48 } 49 50 51 } 52 53 //存放自定义数据类型的 指针 54 void test02() 55 { 56 vector<Person*>v; 57 58 Person p1("张三", 10); 59 Person p2("李四", 80); 60 Person p3("王五", 40); 61 Person p4("赵六", 30); 62 Person p5("孙七", 30); 63 64 //向容器长添加数据 65 66 v.push_back(&p1); 67 v.push_back(&p2); 68 v.push_back(&p3); 69 v.push_back(&p4); 70 v.push_back(&p5); 71 72 73 //遍历容器 74 for (vector<Person*> ::iterator it = v.begin(); it != v.end(); it++) 75 { 76 cout << "2姓名:" << (*it)->m_Name << " 年龄: " << (*it)->m_Age << endl; 77 } 78 } 79 80 81 82 int main() 83 { 84 85 86 test01(); 87 88 test02(); 89 90 system("pause"); 91 92 return 0; 93 94 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15138328.html