#include <string>
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string,size_t> word_count;
string word;
while(cin >> word)
{
++ word_count[word];
}
for(const auto & w : word_count)
{
cout << w.first << " occurs " << w.second <<
(w.second > 1 ? "times":"time") << endl;
}
return 0;
}
运行如下:
输入
a b abc school school you are a can canner
输出
a occurs 2times
abc occurs 1time
are occurs 1time
b occurs 1time
can occurs 1time
canner occurs 1time
school occurs 2times
you occurs 1time
map和python里面的字典类型相似,用python编写同类型的代码如下:
dict1 = {}
while True:
word = input("") #这里注意python中的input是以'\n'为界的,每次输入后都得换行'\n'
if word == 'q':
break
if word in dict1.keys():
dict1[word] += 1
else:
dict1[word] = 1
str1 = ''
for key in dict1.keys():
if dict1[key] > 1:
str1 = 'times'
else:
str1 = 'time'
print(key + " occurs " + str(dict1[key]) + str1)
在ubuntu中运行如下:
r@r:~/coml_/python/test$ python3 1.py
Enter a name(enter 'q' to quit):a
Enter a name(enter 'q' to quit):b
Enter a name(enter 'q' to quit):c
Enter a name(enter 'q' to quit):a
Enter a name(enter 'q' to quit):b
Enter a name(enter 'q' to quit):q
a occurs 2times
b occurs 2times
c occurs 1time