#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//vector中存放自定义数据类型
class Person{
public:
//构造函数
Person(string name,int age)
{
this->name=name;
this->age=age;
}
string name;
int age;
};
void test1(){
vector<Person> v;
Person p1("aaa",10);
Person p2("bbb",10);
Person p3("ccc",10);
//向容器中添加数据
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
//遍历容器中的数据
for(vector<Person>::iterator it=v.begin();it!=v.end();it++){
cout<<(*it).name<<endl;
}
}
//存放自定义数据类型 指针
void test2(){
vector<Person*>v;
Person p1("aaa",10);
Person p2("bbb",10);
Person p3("ccc",10);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
//容器遍历
for(vector<Person*>::iterator it=v.begin();it!=v.end();it++){
cout<<(*it)->name<<endl;
}
}
int main(){
test1();
test2();
}
容器 vector存放自定义数据类型
最新推荐文章于 2024-03-28 22:04:45 发布