#include<iostream>
#include<vector>
#include<string>
#include<algorithm>//标准算法头文件
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;
};
//vector容器存放自定义数据类型
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++)
{
//it相当于指针有两种方式
//1解引用
cout << "姓名: " << (*it).m_name << " 年龄: " << (*it).m_age << endl;
//2指针用箭头访问
cout << "姓名: " << it->m_name << " 年龄: " << it->m_age << endl;
}
}
//vector容器存放自定义数据类型指针
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)->m_name << " 年龄: " << (*it)->m_age << endl;
}
}
int main() {
test1();
test2();
system("pause");
return 0;
}
STL vector容器存放自定义数据类型
最新推荐文章于 2024-07-12 10:56:01 发布