最近学STL,这是一篇网上看到的很详细的map用法,个人觉得挺适合入门的
,转过来膜拜一下(*^__^*)
参考网址:http://www.kuqin.com/cpluspluslib/20071231/3265.html
注:里面的代码均可以编译通过,居然是作者手写的,超级膜拜~![MAP入门经典(1) MAP入门经典(1)](https://i-blog.csdnimg.cn/blog_migrate/26e349bb637dda6e2df90e94ad4436d8.gif)
Map用法详解:
Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。
下面举例说明什么是一对一的数据映射。比如一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,很明显学号用int描述,姓名用字符串描述(本篇文章中不用char
Map<int,
1. map的构造函数
map共提供了个构造函数,这块涉及到内存分配器这些东西,略过不表,在下面我们将接触到一些map的构造方法,这里要说下的就是,我们通常用如下方法构造一个map:
Map<int,
2.数据的插入
第一种:用insert函数插入pair数据,下面举例说明
(
以下代码虽然是随手写的,应该可以在VC和GCC下编译通过
,大家可以运行下看什么效果,在VC下请加入这条语句,屏蔽警告
#pragma
#include<map>
#include<string>
#include<iostream>
using
int
{
map<int,string>mapStudent;
mapStudent.insert(pair<int,string>(1,"student_one"));
pair<int,string>Sp(2,"student_two");
mapStudent.insert(Sp);
mapStudent.insert(pair<int,string>(3,"student_three"));
map<int,string>::iterator
for(iter
{
cout<<iter->first<<"
}
return
}
pair用法
#include
#include
using
int
{
map<int,
for
{
pair<int,int>
m.insert(p);
}
map<int,int
iend
for
cout
}
第二种:用insert函数插入value_type数据,下面举例说明
#include<map>
#include<string>
#include<iostream>
using
int
{
map<int,string>mapStudent;
mapStudent.insert(map<int
mapStudent.insert(map<int,string>::value_type(2,"student_two"));
mapStudent.insert(map<int,string>::value_type(2,"student_three"));
map<int
for(iter=mapStudent.begin();iter!=mapStudent.end();iter++)
{
cout<<iter->first<<"
}
return
}
第三种:用数组方式插入数据,下面举例说明
#include<map>
#include<string>
#include<iostream>
using
int
{
map<int,string>mapStudent;
mapStudent[1]="student_one";
mapStudent[2]="student_two";
mapStudent[3]="student_three";
map<int,string>::iterator
for(iter
{
cout<<iter->first<<"
}
}