1.介绍
map是STL的关联式容器,以key-value的形式存储,以红黑树(平衡二叉查找树)作为底层数据结构,对数据有自动排序的功能。
其命名空间为std,头文件是map。
C++的map就像Python中的dict。
2.创建
可以使用如下的方法创建:
map<string , int >m1;
map<int ,string >m2;
map<int ,char >m3;
3.增
map<string , int >m1;
m1.insert(pair <string, int>("Apple", 1));
m1.insert(map <string, int>::value_type("Boy",2));
m1["Cat"] = 3;
map统计字符出现的次数
#include <iostream>
#include <map>
using namespace std;
int main()
{
string str = "aaaacccvvvvbbb";
map<char, int>count_char;
for (auto i : str)
{
count_char[i]++;
}
for (auto j : count_char)
{
cout << j.first << ":" << j.second << endl;
}
system("pause");
return 0;
}
4.查
第1种:用count函数来判断关键字是否出现,其缺点是无法定位数据出现的位置,由于map的一对一的映射特性,就决定了count函数的返回值只有两个,要么是0,要么是1,当要判断关键字出现时返回1.
第2种:用find函数来定位数据出现的位置,它返回一个迭代器,当数据出现时,它返回数据所在位置的迭代器;如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";
map<int, string>::iterator iter = mapStudent.find(1);
if (iter != mapStudent.end()) {
cout << "Found, the value is " << iter->second << endl;
}
else {
cout << "Do not found" << endl;
}
cout << "Use count(): "<<mapStudent.count(1) << endl;
system("pause");
return 0;
}
运行结果
Found, the value is student_one
Use count(): 1
5.读
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";
map<int, string>::iterator iter;
cout << "方法1" << endl;
for (auto i : mapStudent)
{
cout << i.first << " " << i.second << endl;
}
cout << "方法2" << endl;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
{
cout << iter->first << " " << iter->second << endl;
}
system("pause");
return 0;
}
6.map的基本操作函数:
C++ Maps是一种关联式容器,包含“关键字/值”对
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数