#include<iostream>
#include<vector>
using namespace std;
class Student
{
public:
string m_Name;
int m_Age;
Student(string name, int age)
{
m_Name = name;
m_Age = age;
}
};
void test()
{
vector<Student> v;
Student stu1("Lucy", 22);
Student stu2("David", 23);
v.push_back(stu1);
v.push_back(stu2);
for (vector<Student>::iterator iter = v.begin(); iter != v.end(); iter++)
{
cout << "Name:" << iter->m_Name << " Age:" << iter->m_Age << endl;
}
cout << "test\n" << endl;
}
void testptr()
{
vector<Student*> v;
Student stu1("Lucy", 22);
Student stu2("David", 23);
//容器中存放的元素均是对象的内存地址
v.push_back(&stu1);
v.push_back(&stu2);
//iter指向容器中的首元素
//通过*iter获得相应位置处的元素即对象的内存地址
//所以*iter是指向对象的指针,再通过->获取对象属性
for (vector<Student*>::iterator iter = v.begin(); iter != v.end(); iter++)
{
cout << "Name:" << (*iter)->m_Name << " Age:" << (*iter)->m_Age << endl;
}
cout << "testptr" << endl;
}
int main()
{
test();
testptr();
}
C++的vector容器存放自定义数据类型操作实例
最新推荐文章于 2023-12-06 09:27:25 发布