map的使用
来源:互联网 发布:美工工作流程 编辑:程序博客网 时间:2024/06/17 13:18
STL中的map容器是我经常用的,但是因为map跟别的容器不太一样,每次用的时候对于map中元素的插入方式总是忘却,故而发篇博文,提醒我也提醒所有人map容器的三种插入方式:
第一种:用insert函数插入pair数据。下面举例说明:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
}
第二种:用insert函数插入value_type数据,下面举例说明:
#include <map>
#include <string>
#include <iostream>
using namespace std;
Int main()
{
}
第三种:用数组方式插入数据,下面举例说明:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
}
以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值,用程序说明:
mapStudent.insert(map<int, string>::value_type (1, "student_one"));
mapStudent.insert(map<int, string>::value_type (1, "student_two"));
上面这两条语句执行后,map中1这个关键字对应的值是“student_one”,第二条语句并没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以用pair来获得是否插入成功,程序如下
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, "student_one"));
我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map的迭代器,如果插入成功的话Insert_Pair.second应该是true的,否则为false。
下面给出完成代码,演示插入成功与否问题:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
}
大家可以用如下程序,看下用数组插入在数据覆盖上的效果
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
}
- 【Map】Map.Entry的使用
- map 文件的使用
- map的使用
- MAP 的使用
- Map接口的使用。。。
- google map的使用
- map的使用:
- map的使用
- map的使用例子
- C++ map的使用
- java Map的使用
- map::insert的使用
- hash map的使用
- std::map的使用
- map容器的使用
- map容器的使用
- map的使用
- C++ map的使用
- Linux之Makefile(addsuffix)
- 详解协方差与协方差矩阵
- Linux之Makefile(addpreffix)
- 【android】android中如何关闭所有的Activity
- Spectral Clustering资料
- map的使用
- uboot命令解析
- 随时随地编写运行调试代码(Android)
- 【软件工程】第一、二章总结
- Linux之Makefile(join)
- python切片用法
- mongodb查询优化
- 博客之旅正式开始!
- POJ 3311-Hie with the Pie(最短路+状压DP)