map集合的用法

map的用法以及可能会犯的错误


1.插入操作与赋值操作(size与empty用法)

#include<map>
#include<iostream>
using namespace std;
int main() {
	map<int, string>m1;
	m1[4] = "大哥";//也可以用at()但这两种不能混用会报错
	m1.insert(make_pair<int, string>(0, "张三"));
	m1.insert(make_pair<int, string>(1, "李四"));
	m1.insert(make_pair<int, string>(2, "王五"));
	m1.insert(make_pair<int, string>(3, "赵六"));
	for (map<int, string>::iterator it = m1.begin(); it != m1.end(); it++) {
		cout << "Key键:" << (*it).first<<" " << "value值:" << (*it).second;
		cout << endl;
	}
	cout << "长度" << m1.size() << endl;
	cout << "是否为空" << m1.empty();
	cout << endl;
}

2.删除与清空操作

	m1.clear();
	m1.erase(m1.begin());//仅仅做演示不能连用的

3.查找操作

#include<map>
#include<iostream>
using namespace std;
int main() {
	map<int, string>m1;
	m1[4] = "大哥";
	m1.insert(make_pair<int, string>(0, "张三"));
	m1.insert(make_pair<int, string>(1, "李四"));
	m1.insert(make_pair<int, string>(2, "王五"));
	m1.insert(make_pair<int, string>(3, "赵六"));
	for (map<int, string>::iterator it = m1.begin(); it != m1.end(); it++) {
		cout << "键:" << (*it).first<<" " << "值:" << (*it).second;
		cout << endl;
	}
	cout << "长度" << m1.size() << endl;
	cout << "是否为空" << m1.empty();
	cout << endl;
	map<int,string>::iterator it=m1.find(1);
	cout << (*it).second;
	cout << endl;
}

4.逆序操作

#include<map>
#include<iostream>
using namespace std;
int main() {
	map<int, string,greater<int>>m1;//未指定默认less
	m1[4] = "大哥";
	m1.insert(make_pair<int, string>(0, "张三"));
	m1.insert(make_pair<int, string>(1, "李四"));
	m1.insert(make_pair<int, string>(2, "王五"));
	m1.insert(make_pair<int, string>(3, "赵六"));
	for (map<int, string,greater<int>>::iterator it = m1.begin(); it != m1.end(); it++) {
		cout << "键:" << (*it).first<<" " << "值:" << (*it).second;
		cout << endl;
	}
	cout << "长度" << m1.size() << endl;
	cout << "是否为空" << m1.empty();
	cout << endl;
	map<int,string>::iterator it=m1.find(1);
	cout << (*it).second;
	cout << endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值