C++primer学习:关联容器(2)

pair对象的创建方式

using P = pair<string, int>;
int main()
{
    vector<P> data;
    string word;
    int interger;
    while (cin >> word >> interger)
        data.emplace_back(word, interger);//最简单
    /* data.push_back(pair<string, int>(word, interger));*/
        //data.push_back(make_pair(word, interger));
        //data.push_back({ word, interger });

    for (const auto it : data)
        cout << it.first << " " << it.second << endl;

改写家庭与孩子的map,添加一个pair的vector保存孩子的名和生日.

using P = pair<string, string>;
using Children = vector<P>;
int main()
{

    map<string, Children> family;
    string f_name, c_name,birthday;
    while (cout<<"last_name: "&&cin>>f_name)
    {
        while (cout<<"child_name: birthday data: "&&cin>>c_name>>birthday)
            family[f_name].emplace_back(c_name, birthday);
        cin.clear();
    }

    for (const auto it : family)
    {
        cout << endl << it.first << ":\n";
        for (const auto child : it.second)
        {
            cout << child.first << " birthday: " << child.second << endl;
        }
    }

insert操作:向关联容器添加元素

    map<string, int>  word_count;
    string word;
    while (cin>>word)
    {
        auto ret = word_count.insert({word,1});//返回一个pair对象,first是一个指向插入元素的迭代器,second是一个bool变量
        if (ret.second)
            ++(ret.first->second);
    }

对multimap添加元素,不能使用下标运算.

multimap<string,vector<string >>  word_count;
    string word,name;
    while (cin >> word)
    {   
        vector<string> ch;
        while (cin >> name)
            ch.push_back(name);
        word_count.insert({ word, ch });
        cin.clear();
    }
    for (auto &it : word_count)
    {   
        cout << it.first << " : ";
        for (auto &child : it.second)
        cout <<" " <<child;
    }

你可能感兴趣的:(C++primer学习:关联容器(2))