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插
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值