map使用

133 阅读1分钟

有效的括号

20. 有效的括号

使用方法见中的思路2

统计字符串中各字母对应个数

CPP50 统计字符串中各字母字符对应的个数

map <char,int> mp;
for(int i = 0; str[i] != '\0'; i++)
{
    if(isalpha(str[i])) mp[str[i]]++;
}
for(auto it = mp.begin(); it != mp.end(); it++)
{
    cout<< it->first << ':' << it->second << endl;
}

key point

  1. map中value的值不仅是0或1
  2. 想要同时访问map中的key和value,只能使用iterator
  3. auto自动识别数据类型,可以用来代替map<char,int>::iterator it方便书写和阅读

判断元素是否出现(查询)

CPP71 判断元素是否出现

map<int,int> mp;
int tmp;
for(int i = 0; i < n; i++) 
{
    cin>>tmp;
    mp.insert({tmp,1});
}
int ques;
while(m)
{
    m--;
    cin>>ques;
    if(mp.count(ques)) cout<<"yes"<<endl;
    else cout<<"no"<<endl;
}

key point

  1. map.insert()的使用:要成对插入。
  • map.insert({key,value})
  • map.insert(make_pair(key,value))