C++ map简单demo(二十七)

1.示例一:map<int, int> mp;用法

#include <iostream>
#include <map>
using namespace std;

int main(){
  map<int, int> mp;
  for (int i = 0; i < 20; i++){
    mp.insert(make_pair(i, i));
  }

  map<int, int>::iterator it_find;
  it_find = mp.find(1);//查找key为的1键值
  cout << it_find->first <<" -> " << it_find->second << endl << endl;
  
  map<int, int>::iterator it;
  for (it = mp.begin(); it != mp.end(); it++){
    cout << it->first << " -> " << it->second << endl;
  }
  return 0;
}
2.示例二:map<string, unique_ptr<int>> myMap;用法
#include <iostream>
#include <map>
#include <memory>
using namespace std;

int main() {
  map<string, unique_ptr<int>> myMap;

  //1.向map中插入值int类型
  myMap["key1"] = make_unique<int>(10);
  myMap["key2"] = make_unique<int>(20);
  myMap["key3"] = make_unique<int>(30);

  //2.修改"key2"的值.
  cout << "key2 = " << *myMap["key2"] << endl;
  *myMap["key2"] = 50;
  cout << "修改:key2 =  " << *myMap["key2"] << endl;

  //3.访问map中存储的值.
  for(const auto& pair : myMap) {
    cout << pair.first << " = " << *pair.second << endl;
  }

  //2.向map中插入值string类型
  map<string, unique_ptr<string>> stu;
  stu["name"] = make_unique<string>("Mr Li");
  stu["school"] = make_unique<string>("HFOO");

  printf("\nxxx------line = %d, name = %s\n",__LINE__,(*stu["name"]).c_str());
  *stu["name"] = string("Mr Wang");
  printf("xxx------line = %d, name = %s\n\n",__LINE__,(*stu["name"]).c_str());

  for(const auto &pair : stu)
    printf("xxx------line = %d, %s = %s\n",__LINE__,(pair.first).c_str(),(*pair.second).c_str());

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android系统攻城狮

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值