C++ STL之映射map的使⽤

C++ STL之映射map的使⽤
map 是键值对,⽐如⼀个⼈名对应⼀个学号,就可以定义⼀个字符串 string 类型的⼈名为“键”,学
号 int 类型为“值”,如 map< string, int> m; 当然键、值也可以是其它变量类型~ map 会⾃动将所有的
键值对按照键从⼩到⼤排序, map 使⽤时的头⽂件 #include < map> 以下是 map 中常⽤的⽅法:

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
 map<string, int> m; // 定义⼀个空的map m,键是string类型的,值是int类型的
 m["hello"] = 2; // 将key为"hello", value为2的键值对(key-value)存⼊map中
 cout << m["hello"] << endl; // 访问map中key为"hello"的value, 如果key不存在,则返回0
 cout << m["world"] << endl;
 m["world"] = 3; // 将"world"键对应的值修改为3
 m[","] = 1; // 设⽴⼀组键值对,键为"," 值为1
 // ⽤迭代器遍历,输出map中所有的元素,键⽤it->first获取,值⽤it->second获取
 for (auto it = m.begin(); it != m.end(); it++) {
 cout << it->first << " " << it->second << endl;
 }
 // 访问map的第⼀个元素,输出它的键和值
 cout << m.begin()->first << " " << m.begin()->second << endl;
 // 访问map的最后⼀个元素,输出它的键和值
 cout << m.rbegin()->first << " " << m.rbegin()->second << endl;
 // 输出map的元素个数
  cout << m.size() << endl;
 return 0;
}

当map内元素值为int类型或常量时,默认值为0。

当为String类型时,默认值不明,不显示。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值