C++STL中map常见用法

  • 自动建立Key-value的对应。key 和 value可以是任意你需要的类型。
  • 根据key值快速查找记录,查找的复杂度基本是log(N)。
  • 快速插入Key -Value 记录。
  • 快速删除记录。
  • 根据Key 修改value记录。
  • 遍历所有记录。
常见用法
#include<bits/stdc++.h>
#include<map>
using namespace std;
map<int, char> mp;
int main() {
	for(int i=0; i<3; i++) mp[i] = (char)(i + 'a');
	
	//常规用法 
	map<int, char>::iterator it;//迭代器 
	for(it=mp.begin(); it!=mp.end(); it++){
		cout << it->first << " " << it->second << endl;
	}
	
	//直接输出 
	cout << mp[1] << endl;
	
	//便捷用法
	for(auto it: mp){
		cout << it.first << " " << it.second << endl;
	}
	
	map<int, string> mp1;
	for(int i=0; i<3; i++) mp1[i] = "abcd"; 
	
	map<int, string>::iterator it1;
	for(it1=mp1.begin(); it1!=mp1.end(); it1++){
		cout << it1->first << " " << it1->second << endl;
	}
	
	//直接输出 
	cout << mp1[1][0] << endl;
	
	/*
	这里解释一下,你可以看map的值是什么类型来判断用
	比如:map<int, string> 那 map[i]就是一个string,
	map<int, char> map[i]就是一个字符
	map<int, vector<int> >  map<i>就是一个 vector 
	类似用法有很多 
	*/ 
	
	map<int, vector<int> > mp2;
	//mp2[i]就可以直接当成vector使用  
	for(int i=1; i<=10; i++){
		mp2[1].push_back(i);
	}
	int len = mp2[1].size();
	for(int i=0; i<len; i++){
		cout << mp2[1][i] << " ";
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值