map<string,int> mp;
string name;
int score;
cin >> name >> score;
mp.insert(make_pair(name,score));
cout << mp["lily"];//返回的是lily对应的score的值
比如说:cin : lily 78
则cout: 78
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<string,int> mp;
string name;
int score;
cin >> name >> score;
mp.insert(make_pair(name,score));
cout << mp["lily"] << endl;
return 0;
}
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct Student{
string name;
int score;
};
Student s[5] = {{"Jack",89},{"jh",78},{"sd",54},{"sf",65},{"trr",90}};
typedef map<string,int> MP;
int main()
{
MP mp;
for(int i = 0; i < 5; ++ i)
mp.insert(make_pair(s[i].name,s[i].score));
cout << mp["Jack"] << endl;//89
mp["jh"] = 90;
MP::iterator p;
for(p = mp.begin(); p != mp.end(); ++ p)
cout << p->first << " " << p->second << endl;
Student st;
st.name = "Jack";
st.score = 99;
pair<MP::iterator,bool> p2 = mp.insert(make_pair(st.name,st.score));
if(p2.second)//p.first为MP::iterator
{
cout << p2.first->first << " " << p2.first->second << " " << "is inserted" << endl;
}
else
cout << "failed" << endl;
Student st2;
st2.name = "Ja";
st2.score = 99;
pair<MP::iterator,bool> p3 = mp.insert(make_pair(st2.name,st2.score));
if(p3.second)//p.first为MP::iterator
{
cout << p3.first->first << " " << p3.first->second << "is inserted" << endl;
}
else
cout << "failed" << endl;
mp["Harry"] = 78;
MP::iterator q = mp.find("Harry");//查找的是关键字first
cout << q->first << " " << q->second << endl;
return 0;
}
本题主要是注意两个地方:
1. 对出现的单词计数
2. 对单词排序,排序规则为:先按次数多的输出,如果次数相等,按照字典序从小到大输出。
对单词计数可以采用map对出现的单词进行计数,map<string,int> mp,关键字为string, mp[s]的值即为s对应的次数,刚开始默认为0.
对单词排序,可以采用set,先将mp中的单词插入到set中,然后set按照排序规则输出即可。
#include<iostream>
#include<map>
#include<set>
#include<string>
using namespace std;
struct Word{
int times;
string words;
};
struct rule{
bool operator()(const Word &a1, const Word &a2)
{
if(a1.times != a2.times)
return a1.times > a2.times;
else
return a1.words < a2.words;
}
};
int main()
{
freopen("13.4.txt","r",stdin);
map<string,int> mp;
set<Word,rule> st;
string s;
while(cin >> s)
{
++mp[s];//mp[s]返回的是与s对应的second,即int类型的次数,累计单词出现的次数
}
map<string,int>::iterator p1;
for(p1 = mp.begin(); p1 != mp.end(); ++p1)//将mp中的数存在set中 (set中不含重复元素)
{
Word a;
a.times = p1->second;
a.words = p1->first;
st.insert(a);
}
set<Word,rule>::iterator p2;
for(p2 = st.begin(); p2 != st.end(); ++p2)//set按照rule规则排序后输出
cout << p2->words << " " << p2->times << endl;
return 0;
}