The following code demonstrates how to use the map<string, int>
to count occurrences of words. It uses the word as the key and the count as the value.
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, int> wordcounts;
std::string s;
while (std::cin >> s && s != "end")
++wordcounts[s];
while (std::cin >> s && s != "end")
std::cout << s << ' ' << wordcounts[s] << '\n';
}
The following code demonstrates how to use the map<string, int>
insert function to construct index.
#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef map<string,int>::value_type pairDict;
int main()
{
map<string,int> dict;
char name[100];
int i=0;
while(EOF!=scanf("%s",name))
{
dict.insert(pairDict(string(name),i++));
}
return 0;
}