C++ 之 Map

Map


map 是C++ STL中的关联容器, key-Value键值对存储,一对一的映射关系。

内部结构采用的是红黑树, 它会实现对数据的自动排序 ,所以map内部所有的数据都是有序的。这样的处理可以帮助我们解决很多问题。

#include 

定义的结构: map<数据类型1, 数据类型2> 变量名

map<int, int> m1;
map<int, string> m2;

std::unordered_map<std::string, Texture2D*> _textures;
Map<std::string, SpriteFrame*> _spriteFrames;
Map<std::string, Animation*> _animations;

常用的方法:

  • empty 检测是否为空

  • find 返回key所在的位置

  • size 返回map映射中的对数

  • clear 清空map中的所有元素

  • begain 返回头部的迭代器

  • end 返回尾部+1的迭代器

  • rebegin 返回尾部的迭代器

  • rend 返回头部-1的迭代器

  • insert 插入元素

// 插入pair对象
m1.insert(pair<int, string>(1, "str"));
// 插入value_type数据
m1.insert(map<int, string>::value_type(2, "str"));
// 通过赋值方法插入
m1[111] = "666"
  • erase 删除元素
// 删除元素的迭代器
m2.erase(it);
// 删除元素的key
m2.erase(key);
// 删除指定范围内的元素
m2.erase(first, last);	

基本使用:

#include
#include
using namespace std;
int main() {
	map<int,string> m1;
	m1[1]="ctx";
	m1[2]="cxt";
	m1[3]="txc";
	m1[10]="txt";
	m1[5]="666";
	map<int,string>::iterator it;
	for(it=m1.begin();it!=m1.end();it++)
	{
		cout<< it->first <<" "<< it->second <<endl;
	}
	//it->为Key,it->second为Value 
}

你可能感兴趣的:(C++,c++)