对于map容器,如果下标所表示的键在容器中不存在,则添加新元素。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string, int > wordCount;
string word;
cout << "Enter some words(ctrl+Z to end)" << endl;
while (cin >> word)
++wordCount[word];
cout << "word\t\ttimes" << endl;
for (map<string ,int >::iterator iter = wordCount.begin(); iter != wordCount.end() ; iter++)
{
cout << (*iter).first << "\t\t" << (*iter).second << endl;
}
system("pause");
return 0;
}
方法二:
从文件中读取数据
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
ifstream ifs(".\\Debug\\Data.txt",ios_base::in);
char input[100];
int size = 100;
char *delim = " ,.?!-'\"";
char *temp;
map<string, int> wordCount;
if (!ifs)
{
cout << "The file can't open!";
exit(1);
}
while (ifs&&!ifs.eof())
{
ifs.getline(input, 100);
temp = strtok(input,delim);
while (temp!=NULL)
{
string s = temp;
transform(s.begin(), s.end(), s.begin(), tolower);
++wordCount[s];
temp = strtok(NULL, delim);
}
}
for (map<string,int>::iterator iter = wordCount.begin(); iter != wordCount.end(); iter++)
{
cout << (*iter).first << "\t\t" << (*iter).second << endl;
}
system("pause");
return 0;
}