練習 6.22

6.22:列出可能的三種應用,它們都會用到map, 寫出每個map的定義,說明怎樣插入元素和獲取元素。




#include <iostream>
#include <vector>
#include <string>
#include <map>


using namespace std;


int main()
{
    //學號 姓名 map<string,string>


    map<string,string>student_map;
    typedef map<string, string>::value_type valType;
    map<string,string>::iterator iter;


    student_map.insert(valType("1","a"));
    student_map.insert(valType("2","b"));
    student_map.insert(valType("3","c"));


    for(iter=student_map.begin();iter!=student_map.end();++iter)
        cout<<"number: "<<(*iter).first<<" name:  "<<(*iter).second<<endl;


    cout<<endl;


   //學號 姓名 map<string,vector<string>>
    typedef map<string,string>::value_type valType;
    typedef vector<string> student;
    map<string,student>students;
    students["1"].push_back("zhang san");
    students["2"].push_back("li si");
    students["3"].push_back("wang wu");
    students["4"].push_back("zhao liu");


    map<string,student>::iterator siter;
    student::iterator it;
    for(siter=students.begin(); siter != students.end();++siter)
        for(it=(*siter).second.begin();it!=(*siter).second.end(); ++it)
        cout<<"number: "<<(*siter).first<<" name: "<<(*it)<<endl;


    cout<<endl;


  //學號 姓名 年齡 map<string,vector<pair<string, int >>>
    typedef pair<string,int> student_infor;
    typedef vector<student_infor> student3;
    map<string,student3> student_map3;
    map<string,student3> ::iterator iter3;
    student3::iterator iter_infor;


    student_map3["5"].push_back(make_pair("d",20));
    student_map3["6"].push_back(make_pair("e",21));
    student_map3["7"].push_back(make_pair("e",22));
    student_map3["8"].push_back(make_pair("f",25));


    for(iter3=student_map3.begin();iter3!=student_map3.end();++iter3)
        for(iter_infor=(*iter3).second.begin();iter_infor!=(*iter3).second.end();++iter_infor)
           cout<<"number: "<<(*iter3).first<<" name: "<<(*iter_infor).first
           <<" age: "<<(*iter_infor).second<<endl;


    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章