poj 2418 Hardwood Species --- 再来复习遍map吧

题目是统计字符串出现的频率,应该是用二分排序树做的吧。

这里 8000多ms。。

输入输出纠结死我了。。。

再记一遍


输入:

map<int, string> mapStudent;

1、mapStudent.insert(pair<int, string>(1, “student_one”));

2、mapStudent.insert(map<int, string>::value_type (2, “student_two”));

3、mapStudent[3] = “student_three”;

前两种方法,在出现重复的值时不能使用,而第三种可以直接覆盖。


遍历:

1、利用前向迭代器

map<int, string>::iterator iter;

for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

      cout<<iter->first<<” ”<<iter->second<<end;

                             ↓                                    ↓

           map<      int,                             string>


2、利用反向迭代器

map<int, string>:::reverse_iterator iter;                  ↓ 这里有r 哦

for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)

        cout<<iter->first<<” ”<<iter->second<<end;


3、数组遍历

int nSize = mapStudent.size();

for(int nIndex = 1; nIndex <= nSize; nIndex++)

        cout<<mapStudent[nIndex]<<end;


4、清空

用.clear()函数清空

用.empty()判断是否为空


4、删除

//如果要删除1,用迭代器删除

map<int, string>::iterator iter;

iter = mapStudent.find(1);

mapStudent.erase(iter);


//如果要删除1,用关键字删除

Int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0


//用迭代器,成片的删除

//一下代码把整个map清空

mapStudent.earse(mapStudent.begin(), mapStudent.end());

//成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合



PS:%.4f能过 %.4lf不能过╮(╯▽╰)╭


#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#define inf 0x3f3f3f3f
using namespace std;

int cnt;
string s;

int main()
{
    cnt=0;
    map<string,int> ty;
    while(getline(cin,s))
    {
        ty[s]++;
        cnt++;
    }
    map<string,int>::iterator iter;
    for(iter=ty.begin();iter!=ty.end();iter++)
    {
        cout<<iter->first;
        printf(" %.4f\n",(iter->second*100.0)/cnt);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值