C++ map总结
目录
介绍
map是STL的一个关联容器,它提供一对一的hash。
- 第一个可以称为关键字(key),每个关键字只能在map中出现一次;
- 第二个可能称为该关键字的值(value);
map以模板(泛型)方式实现,可以存储任意类型的数据,包括使用者自定义的数据类型。Map主要用于资料一对一映射(one-to-one)的情況,map內部的实现自建一颗红黑树,这颗树具有对数据自动排序的功能。在map内部所有的数据都是有序的,如下图:
常用函数
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
insert()插入元素
max_size()返回可以容纳的最大元素个数
size() 返回map中元素的个数
swap() 交换两个map
get_allocator() 返回map的配置器
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数
函数实例
插入元素,并判断是否插入成功
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<int, string> myMap;
// 第一种 用insert函數插入pair
myMap.insert(pair<int,string>(01, "aa"));
// 第二种 用insert函数插入value_type数据
myMap.insert(map<int, string>::value_type(02, "bb"));
// 第三种 用"array"方式插入
myMap[33] = "cc";
// 构造定义,返回一个pair对象,验证是否添加成功
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = myMap.insert(map<int, string>::value_type(33, "cc"));
if (!Insert_Pair.second)
cout << "Error insert new element" << endl;
cout << "\n";
return 0;
}
遍历map
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> m;
for (int i = 0; i < 5; i++) {
m[i] = i * i;
}
//第一种遍历方式,迭代器+while
map<int, int>::iterator iter;
iter = m.begin();
while (iter != m.end()) {
cout << iter->first << "-" << iter->second << endl;
iter++;
}
//第二种遍历方式,for+迭代器
for (iter = m.begin(); iter != m.end(); iter++) {
cout << iter->first << "-" << iter->second << endl;
}
//第三种遍历方式,for+auto
for (auto &it : m) {
cout << it.first << "-" << it.second << endl;
}
return 0;
}
查找元素
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> m;
for (int i = 0; i < 5; i++) {
m[i] = i * i;
}
auto it = m.find(3);
if (it != m.end())
{
int ss = (*it).second;//或者int ss=it->second
cout << ss << endl;
}
return 0;
}
删除元素
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> m;
for (int i = 0; i < 5; i++) {
m[i] = i * i;
}
//删除键为bfff指向的元素
m.erase(4);
//删除迭代器 key所指向的元素
map<int, int>::iterator key = m.find(2);
if (key != m.end())
{
m.erase(key);
}
//删除所有元素
m.erase(m.begin(), m.end());
return 0;
}
统计key的出现的次数
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> m;
for (int i = 0; i < 5; i++) {
m[i] = i * i;
}
int c = m.count(1);
cout << c << endl;
return 0;
}
相关文章
- C/C++的sizeof
- C/C++基础讲解(九十七)之综合实例篇(进销存管理系统)
- atitit.GUI图片非规则按钮跟动态图片切换的实现模式总结java .net c# c++ web html js
- 二叉树的前序遍历(C++)
- 搜狗面试的经典题(C++map按值排序,class struct的差别)
- C++按map的value进行排序
- C++之友元函数与友元类使用(一百一二十一)
- C++之map/set与undered_map/undered_set区别(一百一十八)
- C++ STL源代码学习(map,set内部heap篇)
- C++定期删除旧的日志文件(日志文件存在指定的目录中)
- 【C++】第十一篇(基础)STL map创建、遍历、插入、删除等(详解)
- 【跟学C++】C++映射类——map/multimap类(Study17)
- DSA 经典数据结构与算法 学习心得和知识总结(一) |排序 十大排序算法汇总(C++)