映射:MAP

  map就是从键(key)到值(value)的映射。因为重载了【】运算符,map像是数组的“高级版”。map是键值对,⽐如⼀个⼈名对应⼀个学号,就可以定义⼀个字符串string类型的⼈名为“键”,学号int类型为“值”,如map<string, int> m;当然键、值也可以是其它变量类型~map会⾃动将所有的键值对按照键从⼩到⼤排序,以下是map中常⽤的⽅法:

#include <iostream>

#include <map>

#include <string>

using  namespace  std;

int main() {

map<string, int> n;

// 定义⼀个空的map m,键是string类型的,值是int类型的

n["hai"] = 2;

// 将key为"hai", value为2的键值对(key-value)存⼊map中

cout << m["hai"] << endl;

// 访问map中key为"hai"的value, 如果key不存在,则返回0

cout << m["word"] << endl;

n["word"] = 3;

// 将"word"键对应的值修改为3

n[","] = 1;

// 设⽴⼀组键值对,键为"," 值为1

// ⽤迭代器遍历,输出map中所有的元素,键⽤it->first获取,值⽤it->second获取

for (auto it = n.begin(); it != n.end(); it++) {

cout << it->first << " " << it->second << endl;

}

// 访问map的第⼀个元素,输出它的键和值

cout << n.begin()->first << " " << n.begin()->second << endl;

// 访问map的最后⼀个元素,输出它的键和值

cout << n.rbegin()->first << " " << n.rbegin()->second << endl;

// 输出map的元素个数

cout << n.size() << endl;

return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值