C++ primer 第十章參考答案 10.9

來源:互聯網
上載者:User

 

習題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).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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.