-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path03_vector存放自定义数据类型.cpp
76 lines (66 loc) · 1.38 KB
/
03_vector存放自定义数据类型.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
using namespace std;
// 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("a", 20);
Person p2("b", 21);
Person p3("c", 22);
Person p4("d", 23);
Person p5("e", 23);
// 向容器中添加数据
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
<< "\t年龄" << it->m_Age
<< endl;
}
}
// 存放自定义数据类型 指针
void test02()
{
vector<Person *> v;
Person p1("a", 20);
Person p2("b", 21);
Person p3("c", 22);
Person p4("d", 23);
Person p5("e", 23);
// 向容器中添加数据
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
<< "\t年龄" << (*it)->m_Age
<< endl;
}
}
int main()
{
// test01();
test02();
return 0;
}