15.2.2重学C++之【vector容器存放自定义数据类型】

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
#include<vector>
#include<algorithm>


/*
    2.5.2 vector容器存放自定义数据类型
*/


class People
{
public:
    string name;
    int age;

    People(string _name, int _age)
    {
        this->name = _name;
        this->age = _age;
    }
};


void test1()
{
    vector<People> v;

    People p1("tom", 22);
    People p2("amay", 18);
    People p3("sam", 9);

    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);

    for(vector<People>::iterator it=v.begin(); it!=v.end(); it++)
    {
        cout << "name:" << (*it).name << " age:" << (*it).age << endl;
        //技巧:此处解引用*it的数据类型结果==vector<XXX>中的XXX
        cout << "name:" << it->name << " age:" << it->age << endl; //效果同上
    }
}


void test2() //存放自定义数据类型-指针
{
    vector<People*> v;

    People p1("tom", 22);
    People p2("amay", 18);
    People p3("sam", 9);

    v.push_back(&p1); //保存数据地址
    v.push_back(&p2);
    v.push_back(&p3);

    for(vector<People*>::iterator it=v.begin(); it!=v.end(); it++)
    {
        cout << "name:" << (*it)->name << " age:" << (*it)->age << endl;
    }
}


int main()
{
    test1();
    test2();

    system("pause");
    return 0;
}

posted @ 2021-04-22 20:45  yub4by  阅读(157)  评论(0编辑  收藏  举报