C++ STL - map,unordered_map笔记
map
map - 映射,STL容器之一,以红黑树实现,可以将任何基本类型映射到任何基本类型。
1.定义
// map<键key, 值value> mp;
map<string, int> mp;
2.map内的元素访问
1)通过下标访问
// #include<bits/stdc++.h>
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<char, int> mp;
mp['a'] = 10;
mp['a'] = 1;
// 输出结果为1,10会被覆盖
cout << mp['a'] << endl;
return 0;
}
2)通过迭代器访问
// #include<bits/stdc++.h>
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<char, int> mp;
mp['q'] = 10;
mp['a'] = 20;
mp['z'] = 30;
for(map<char, int>::iterator it = mp.begin(); it != mp.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}
// 输出结果为:
// a 20
// q 10
// z 30
// map会以键从小到大的顺序自动排序(a < q < z),因其内部由红黑树实现
3)函数
(1)size() - 返回map中映射的对数
(2)find() - find(key),返回键为key的映射的迭代器
// #include<bits/stdc++.h>
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<char, int> mp;
mp['q'] = 10;
mp['a'] = 20;
mp['z'] = 30;
cout << mp.find('a') -> first << " " << mp.find('a') -> second;
return 0;
}
(3)erase() - 删除单个元素或一个区间内的所有元素
// #include<bits/stdc++.h>
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<char, int> mp;
mp['q'] = 10;
mp['a'] = 20;
mp['z'] = 30;
auto it = mp.find('q');
mp.erase(it, mp.end());
for(auto it = mp.begin(); it != mp.end(); it++)
cout << it->first << " " << it->second << endl;
// 因为map会自动排序,没删之前是按键key的值从小到大排的,只有键'a'在键'q'前面,所以输出结果是:
// a 20
return 0;
}
(4)clear() - 清空map中的所有元素
unordered_map
以散列表实现,用于处理只映射而不按键key排序的要求,其元素排列无序
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<string, int> unMap = {{"语文", 97}, {"数学", 82}, {"体育", 55}};
auto it = unMap.begin();
while(it != unMap.end())
{
cout << it->first << " " << it->second << endl;
it++;
}
return 0;
}
// 输出
// 体育 55
// 语文 97
// 数学 82
// 此处元素的排列顺序是无序的,如果是map类型则会按键key自动排序