STL中map的简单使用

来源:互联网 发布:电子音合成软件 编辑:程序博客网 时间:2024/05/22 09:48

一个小例子统计输入单词的个数

#include <iostream>#include <string>#include <map>using namespace std;int main(){    map<string, int> word_count;    string word;    while (cin >> word && word != "end")        word_count[word]++;    map<string, int>::iterator it;    for (it = word_count.begin(); it != word_count.end(); it++)        cout << it->first << ":" << it->second << endl;    return 0;}

如果下标所表示的键在容器中不在,则添加新元素,这一特性可使程序惊人的简练:

map<string, int>word_count;string word;while(cin>>word)    ++word_count[word];

下面通过一个题目做个map使用的笔记

Problem Description

有一群人,打乒乓球比赛,两两捉对撕杀,每两个人之间最多打一场比赛。
球赛的规则如下:
如果A打败了B,B又打败了C,而A与C之间没有进行过比赛,那么就认定,A一定能打败C。
如果A打败了B,B又打败了C,而且,C又打败了A,那么A、B、C三者都不可能成为冠军。
根据这个规则,无需循环较量,或许就能确定冠军。你的任务就是面对一群比赛选手,在经过了若干场撕杀之后,确定是否已经实际上产生了冠军。

Input

输入含有一些选手群,每群选手都以一个整数n(n<1000)开头,后跟n对选手的比赛结果,比赛结果以一对选手名字(中间隔一空格)表示,前者战胜后者。如果n为0,则表示输入结束。

Output

对于每个选手群,若你判断出产生了冠军,则在一行中输出“Yes”,否则在一行中输出“No”。

Sample Input

3Alice BobSmith JohnAlice Smith5a cc dd eb ea d0

Sample Output

YesNo

附上渣代码:

#include <iostream>#include <map>#include <string>using namespace std;int main(){    int n;    while (cin >> n && n)    {        string name1, name2;        map<string, int> m;        while (n--)        {            cin >> name1 >> name2;            if (m[name1] != 2)            {                m[name1] = 1;            }            m[name2] = 2;        }        int cnt = 0;        map<string, int>::iterator it;        for (it = m.begin(); it != m.end(); it++)        {            if (it->second == 1)            {                cnt++;            }        }        if (cnt == 1)        {            cout << "Yes" << endl;        }        else        {            cout << "No" << endl;        }    }    return 0;}
0 0
原创粉丝点击