一个简单的例子理解C++ map, 运用map统计单词出现的次数

来源:互联网 发布:路由器软件升级好不好 编辑:程序博客网 时间:2024/05/16 04:43

一个简单的例子理解C++ map, 运用map统计单词出现的次数

一个简单的例子理解C++ map, 运用map统计单词出现的次数


map 对象的元素是键值对(key,value),每个key对应一个value, map默认中按key定义的 “ < ” 排序。

key是一个const 对象不可以改变,其类型为map<k,v>::key_type;
value 是一个非const对象,其类型为map<k,v>::mapped_type;

访问map可以用迭代器访问也可以用下标访问:

  1、用迭代器访问:

map<k,v>::iterator iter = m.begin();......

    这时候对迭代器解引用会得到map容器中一个map<k,v>::value_type 类型的值,对于map容器来说该值是pair类型,再标准库中pair在utility 中声明,pair<first,second> first 为const 对象保存key;second为非const对象,保存value。

    在上面的例子中为pair<const string, int>。因此可以使用迭代器来访问map中的所有值。

  2、用下下标访问

    例如在编写下面程序时:

1 map<string, int> word_count; // empty2 // insert default initialized element with key "SK"; then assign 1 to its value3 word_count["SK"] = 1;

  该程序会在map中查找"SK"键,如果查找到则将"SK" 对应的值赋值为 1。但是word_count 初始为空,并不存在"SK"键,因此    word_count["SK"] = 1;将创建一个"SK"键,并将其对应的值初始化为1.

利用这个性质我们可以写一个之前用数组和其他方式实现起来比较麻烦的单词统计程序:


 

复制代码
 1 /*==================================================================*\ 2  * 3  *                    C++ map 运用---统计单词出现的次数 4  * 5  *                       2013/6/7 by 樊列龙 6  * 7 \*==================================================================*/ 8  9 #include <iostream>10 #include <cstdlib>11 #include <string>12 #include <map>13 14 using namespace std;15 16 int main()17 {18     map<string,int> word_count;// empty19 20     string word;21 22     while(cin >> word)23     {24         ++word_count[word];                      // 用下标访问25     }26 27     map<string, int>::iterator iter;             // iter 为pair 类型(value_type)28     29     for(iter = word_count.begin(); iter != word_count.end(); iter++)30     {31         cout << "[" << iter->first << "] = " << iter->second << endl;32     }33 34     return EXIT_SUCCESS;35 }
复制代码

 


测试结果:

复制代码
fanlielongSKloveSKabcaab^Z[SK] = 2[a] = 3[b] = 2[c] = 1[fan] = 1[lie] = 1[long] = 1[love] = 1
复制代码

我们可以看到用迭代器输出的结果是按照键(这里是string)的 " < " 逻辑(这里是s字典顺序)排序的

0 0