unordered_map

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

//详细介绍C++STL:unordered_map - 朤尧 - 博客园 (cnblogs.com)

void display(unordered_map<string, double> myrecipe, string str)
{

    for (auto iter = myrecipe.begin(); iter != myrecipe.end(); ++iter) {
        cout << iter->first << " " << iter->second << endl;
    }
}

int main()
{
    unordered_map<string, double> myrecipe,mypantry = { {"milk",2.0},{"flour",1.5} };

    /****************插入*****************/
    pair<string, double> myshopping("baking powder", 0.3);
    myrecipe.insert(myshopping);                        // 复制插入
//    myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // 移动插入
//    myrecipe.insert(mypantry.begin(), mypantry.end());  // 范围插入
    myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
    myrecipe["coffee"] = 10.0;  //数组形式插入

    display(myrecipe, "myrecipe contains:");

    /*

    /****************查找*****************/
    unordered_map<string, double>::const_iterator got = myrecipe.find("coffee");

    if (got == myrecipe.end())
        cout << "not found";
    else
        cout << "found " << got->first << " is " << got->second << "\n\n";
    /****************修改*****************/
    //myrecipe.at("coffee") = 9.0;
    //myrecipe["milk"] = 3.0;
//    display(myrecipe, "After modify myrecipe contains:");


    /****************擦除*****************/
//    myrecipe.erase(myrecipe.begin());  //通过位置
//    myrecipe.erase("milk");    //通过key
//    display(myrecipe, "After erase myrecipe contains:");

    /****************交换*****************/
//    myrecipe.swap(mypantry);
//    display(myrecipe, "After swap with mypantry, myrecipe contains:");

    /****************清空*****************/
    //myrecipe.clear();
//    display(myrecipe, "After clear, myrecipe contains:");

    
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值