C++ STL之映射map的使用

C++ STL之映射map的使用

map是键值对,⽐比如⼀一个⼈人名对应⼀一个学号,就可以定义⼀一个字符串串string类型的⼈人名为“键”,学号 int类型为“值”,如 map<string, int> m; 当然键、值也可以是其它变量量类型~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;
}
参考

柳神的博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wvdon

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

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

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

打赏作者

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

抵扣说明:

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

余额充值