How to use map (STL)?-

来源:互联网 发布:软件开发日程表 编辑:程序博客网 时间:2024/05/21 22:02

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;}



原创粉丝点击