map在單詞計數程序的應用
map:關聯數組;保存關鍵字——值對
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
map<string,size_t> word_count;
string word;
while(cin>>word)
{
/* istringstream a;
a.str(word);
char b;
a>>b;
cout<<b;
if(b=='\r')
{
cout<<"1";
break;
}*/
++word_count[word];
}
for(const auto &w:word_count)
cout<<w.first<<" occurs "<<w.second<<((w.second>1?" times":" time"))<<endl;
system("pause");
return 0;
}
這裏有一個問題,至今未解決,就是回車不能跳出for循環,暫時用Ctrl+Z或者F6來強行跳出while
結果
w是對word_count的引用
size_t 是一種機器相關的無符號類型,它被設計的足夠大以便能表示內存中任意對象的大小。在cstdef頭文件中定義了size_t類型
set:關鍵字即值,即只保存關鍵字的容器
#include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;
int main()
{
map<string,size_t> word_count;
set<string> exclude ;
//exclude.insert{"The","But","And","Or","An","A","the","but","and","or","an","a"};
exclude.insert("The");
string word;
while(cin>>word)
{
if(exclude.find(word)==exclude.end())
++word_count[word];
}
for(const auto &w:word_count)
cout<<w.first<<" occurs "<<w.second<<((w.second>1?" times":" time"))<<endl;
system("pause");
return 0;
}
此外還應補充的一點是 map 與 set 的關鍵字都是不能改變的