#include<iostream>
using namespace std;
#include<vector>
class person
{
public:
person(string a, int b) :name(a), age(b) {}
string name;
int age;
};
void text01() {
vector<person> v;
person p1("a",11);
person p2("b", 12);
person p3("c", 13);
person p4("d", 14);
person p5("e", 15);
//向容器中加入数据
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->name<<":"<<(*it).age << endl;
}
}
//存放自定义数据类型指针
void text02() {
vector<person*> v;
person p1("a", 11);
person p2("b", 12);
person p3("c", 13);
person p4("d", 14);
person p5("e", 15);
//向容器中加入数据
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)->name << "-" << (*it)->age << endl;
}
}
int main() {
person* p;
p = new person{ "wa",12 };
cout << p->name << endl;
cout << "-------------" << endl;
text01();
cout << "-------------" << endl;
text02();
}
vector容器存放自定义数据类型及指针
最新推荐文章于 2023-09-27 09:05:03 发布