一、简介
Map是STL中一对一的关联容器,其中第一个称为key,Map中的key是唯一的;第二个称为Map的value。Map内部自建一颗红黑树,这棵树内部具有自动排序的功能(key是有序的)。使用时需要引入头文件:#include <map>.对于迭代器来说,可以修改实值,而不能修改key。根据key值快速查找记录,查找的复杂度基本是log(n);
二、map的基本操作
begin() 返回指向map头部的迭代器
end() 返回指向map末尾的迭代器
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
lower_bound() 返回键值>=给定元素的第一个位置
upper_bound() 返回键值>给定元素的第一个位置
insert() 插入元素
clear() 删除所有元素
size() 返回map中元素的个数
swap() 交换两个map。map中的swap不是一个容器中的元素交换,而是两个容器所有元素的交换。
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
key_comp() 返回比较元素key的函数
value_comp() 返回比较元素value的函数
max_size() 返回可以容纳的最大元素个数
三、插入数据
第一种:用insert函数插入pair数据
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;
}
第二种:用insert函数插入value_type数据
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<int, string> mapStudent;
mapStudent.insert(map<int, string>::value_type (1, "student_one"));
mapStudent.insert(map<int, string>::value_type (2, "student_two"));
mapStudent.insert(map<int, string>::value_type (3, "student_three"));
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;
}
第三种:用数组方式插入数据
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<int, string> mapStudent;