hdu 1004 Let the Balloon Rise (STL Map)有关STLMap的插入删除遍历清空等一系列用法

hdu 1004 Let the Balloon Rise (STL Map)有关STLMap的插入删除遍历清空等一系列用法

题目链接: hdu 1004 Let the Balloon Rise (STL Map)
题目描述: 每次给出若干个颜色的气球,求出颜色出现最多的气球颜色,题目保证有唯一的答案。
解题思路: 找到这题的对应关系,每个气球的颜色映射到气球的个数,所以我们很容易想到用STL中的MAP来解决这个问题,如果对STL中的MAP很熟悉的话,那么这道题就非常简单。
代码如下:

#include<bits/stdc++.h>
using namespace std;
map<string, int> balloon;
string color;
int mxn = 0;
string ans;
int main()
{
    int m;
    while(1){
        cin >> m;
        if(m == 0){
            break;
        }
        for(int i = 0; i < m; i++){
            cin >> color;
            if(balloon.count(color) == 0){
                balloon[color] = 1;
            }
            else{
                balloon[color]++;
            }
        }
        map<string, int> ::iterator iter;
        for(iter = balloon.begin(); iter != balloon.end(); iter++){
            if(iter->second > mxn){
                mxn = iter->second;
                ans = iter->first;
            }
        }
        cout << ans << endl;
        balloon.clear();
        mxn = 0;
    }
    return 0;
}

下面是有关STL中MAP的各种操作的方法:
首先map是什么?map是一种关联容器。
map 容器是关联容器的一种。在关联容器中,对象的位置取决于和它关联的键的值。键可以是基本类型,也可以是类类型。字符串经常被用来作为键,如果想要保存姓名和地址的记录,就可以这么使用。名称通常可能是一个或多个字符串。关联容器中的对象位置的确定取决于容器中的键的类型,而且对于特定容器类型的内部组织方式,不同的 STL 有不同的实现。

声明:

map<string, int> balloon;

插入:

balloon[color] = 1; //用数组方式
balloon.insert(make_pair(color, 1));  //用insert方法

查找:

balloon.count(color) == 0;  //用count方法返回Key为color的个数(0/1)
map<string, int> ::iterator iter;
iter = balloon.find(color);  //用find方法,查找是否有Key
if(iter!=balloon.end())      //找不到返回的是balloom.end()

遍历:

 map<string, int> ::iterator iter;
        for(iter = balloon.begin(); iter != balloon.end(); iter++){
        }
 也可以用while()

删除:
像下面这样的一个例子就是错误的写法,
eg2:

for(ITER iter=mapTest.begin();iter!=mapTest.end();++iter)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter);
}

这是一种错误的写法,会导致程序行为不可知.究其原因是map 是关联容器,对于关联容器来说,如果某一个元素已经被删除,那么其对应的迭代器就失效了,不应该再被使用;否则会导致程序无定义的行为。
可以用以下方法解决这问题:
正确的写法
1.使用删除之前的迭代器定位下一个元素。STL建议的使用方式

for(ITER iter=mapTest.begin();iter!=mapTest.end()
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter++);
}
  1. erase() 成员函数返回下一个元素的迭代器
for(ITER iter=mapTest.begin();iter!=mapTest.end()
{
cout<<iter->first<<":"<<iter->second<<endl;
iter=mapTest.erase(iter);
}

删除操作参考:正确使用stl map的erase方法
清空:

balloon.clear();//用clear方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值