習題10.9 編寫程式統計並輸出所讀入的單詞出現的次數
方法一:
#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
int main()
{
map<string,int> word_count;
string word;
while(cin>>word)
{
++word_count[word];
}
for(map<string,int>::iterator map_it = word_count.begin();map_it!=word_count.end();++map_it)
cout<<map_it->first<<" "<<map_it->second<<endl;
cout<<endl;
return 0;
}
方法二:
#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
int main()
{
map<string,int> word_count;
string word;
while(cin>>word)
{
pair<map<string,int>::iterator,bool> p = word_count.insert(make_pair(word,1));
/*
p為pair類型變數,第一個元素為map<string,int>容器的迭代器,第二個元素為bool類型。insert操作在word_count容器中加入一個鍵為string word,值為int 1的對象;insert操作返回pair賦給p,則p的第一個元素迭代器指向的鍵為string word,且當word在word_count中不存在時p的第二個元素為true,存在時為false。後面的語句if(p.second == false)即判斷當word在word_count中存在時,執行if語句內操作。
*/
if(p.second==false)
{
++p.first->second;
/*
可理解為:
p.first為指向word_count容器內鍵為string word對象的迭代器,對其解引用得到word_count容器內鍵為string word的對象,該物件類型為map<string,int>::valut_type。value_type為pair類型,對該對象執行.second得到第二個元素類型為int,在該程式內即為word出現的數量。最後對該int類型的第二元素執行自增操作。
*/
}
}
for(map<string,int>::iterator map_it = word_count.begin();map_it!=word_count.end();++map_it)
cout<<map_it->first<<" "<<map_it->second<<endl;
cout<<endl;
return 0;
}