C++ map STL映射 简单学习

map 概述:


  • map是一种映射,例如存储int类型数据的数组就是int 类型的下标对值int 的映射,字符数组就是int(称之为键) 对 char 的映射,但是STL 中的map 使得映射的 键 多样化,可以使字符串,浮点型,字符型,string ,等STL 容器 都可以成为map 的键。
  • map 的声明和访问:这里定义了一个string 对 int 的映射,并通过类似数组的下标访问方式,注意键是唯一的,相同的键赋值会导致数据覆盖。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
	map<int ,int > array;
	map<string ,int> str;
	str["123"]=123;
	str["123"]=456;
	cout<<str["123"]<<endl;
	printf("%d",str["123"]);
}
  • 用迭代器访问map :map迭代器的声明与其他stl容器类似,用it->first 访问map当前映射的键,用it->second 访问当前映射的值;
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
	map<int ,int > array;
	map<string ,int> str;
	str["123"]=123;
	str["987"]=159;
	str["124"]=456;
	  map<string,int>::iterator it=str.begin();
	for(;it!=str.end();it++)
	{
		cout<<it->first;
		printf(" %d\n",it->second);
	 } 
}
输出:
、、、、、
123 123
124 456
987 159
、、、、、
  • 我们注意到map 的键会从小到大自动排序,这是因为map内部和set一样都是由红黑树实现的,在建立的时候会自动从小到大排序。

map常用函数


  • find(key)函数返回对应键key 的迭代器:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
	map<int ,int > array;
	map<string ,int> str;
	str["123"]=125;
	str["987"]=159;
	str["124"]=456;
	map<string,int>::iterator it;
	it=str.find("123");
	cout<<it->first;
	printf(" %d\n",it->second);
}
、、、、、
123 125
、、、、、
  • clear()清空元素;
  • erase(it)删除指定迭代器的元素,erase(key) 删除指定键key的元素;
  • erase(first,last ),删除区间【first,last) 的元素
  • size()返回映射总 对 数

版权声明:本文为weixin_45981887原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。