1. 程式人生 > 其它 >c++ 的map第一個例子

c++ 的map第一個例子

技術標籤:c++

#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中執行如下:

[email protected]:~/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