3月PAT考试准备
STL库使用
map使用:
用途:map用于建立不同数据类型之间的映射关系
常用方法:
.count() 用于查看是否存在一对映射关系,若存在该键值存在映射则返回1,否则返回0
迭代器定义语句 map<变量类型,变量类型>::iterator (迭代器名称)
通过迭代器遍历map:
假设 it为迭代器名称,m为与it具有同种映射的map,则遍历语句为:
for(it=m.begin();it!=m.end();it++)
注意: 结束条件是it!=m.end() 迭代器不等于指针
具体例子:
#include<cstdio>
#include<cstdlib>
#include<string>
#include<vector>
#include<map>
#include<iostream>
using namespace std;
int main()
{
string str;
cin>>str;
map<char,int> cnt;
vector<char> letter;
for(int i=0;i<str.length();i++)
{
if(cnt.count(str[i])==0)
{
letter.push_back(str[i]);
cnt[str[i]]=1;
}else
{
cnt[str[i]]++;
}
}
//定义一个迭代器
map<char,int>::iterator iter;
for(iter=cnt.begin();iter!=cnt.end();iter++)
{
printf("%c %d\n",iter->first,iter->second);
}
system("pause");
return 0;
}
unordered_map使用:
使用要求:
#include<unordered_map>
using namespace std;
特点:
map相比unorder_map查找速度更快,但是内部元素的无序排列的
使用:
赋初值:
unordered_map<int, string> myMap={{ 5, "张大" },{ 6, "李五" }};//使用{}赋值
myMap[2] = "李四"; //使用[ ]进行单个插入,若已存在键值2,则赋值修改,若无则插入。
myMap.insert(pair<int, string>(3, "陈二"));//使用insert和pair插