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;
}
本文通过两个示例介绍了如何利用C++标准库中的map<string,int>来实现单词计数和构造索引的功能。第一个示例展示了如何记录文本中各个单词出现的次数;第二个示例则介绍了如何使用map的insert方法建立字符串与其对应序号之间的映射。
882

被折叠的 条评论
为什么被折叠?



