C++ Primer 11章习题

本文通过几个实例展示了C++标准模板库中Map和Vector的使用方法,包括如何使用Map进行关键字与值的对应存储及查找,以及利用Vector存储成对的数据。还介绍了如何在Map中存储更复杂的数据结构,例如将多个名字与同一个姓氏关联。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

11.1 map是两种类型的一一对应,vector是一种类型的容器。
11.2 略
11.3

int main(int argc, char* argv[])
{
    map<string, int> stupidmap;
    string strtemp;
    while (cin >> strtemp)
        ++stupidmap[strtemp];
    for (const auto& c : stupidmap)
        cout << c.first << " " << c.second << endl;
    return 0;
}

11.4 略
11.5 map关键字和值一一对应,set只记关键字
11.6 顺序或按位置访问成员用list
检查成员是否在容器中用set
11.7

void add_lastname(map<string, vector<string>> &maptemp, const string &lastname)
{
    maptemp[lastname];
}
void add_firstname(map<string, vector<string>> &maptemp, const string &lastname, const string &firstname)
{
    maptemp[lastname].push_back(firstname);
}

int main(int argc, char* argv[])
{
    map<string, vector<string>> stupidmap;
    string firsttemp, secondtemp;
    cout << "输入姓氏+空格+名字" << endl;
    while (cin >> firsttemp)
    {
        cin >> secondtemp;
        add_firstname(stupidmap, firsttemp, secondtemp);
    }
    for (const auto &c : stupidmap)
    {
        for (const auto &b : c.second)
            cout << c.first << " " << b << endl;
    }
    return 0;
}

11.8 快速找出元素是否在容器内
11.9 map

int main(int argc, char* argv[])
{
    vector<pair<string, int>> vectemp;
    string strtemp;
    int inttemp;
    cout << "输入string和int序列" << endl;
    while (cin >> strtemp)
    {
        cin >> inttemp;
        vectemp.push_back({ strtemp,inttemp });
    }
    for (const auto &c : vectemp)
        cout << c.first << " " << c.second << endl;
    return 0;
}

11.13-11.14略
11.15 vector,int,map

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值