一个简单的例子理解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; // empty
2 // insert default initialized element with key "SK"; then assign 1 to its value
3 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;// empty
19 
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 }

 

测试结果:

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

fan
lie
long
SK
love
SK
a
b
c
a
a
b
^Z
[SK] = 2
[a] = 3
[b] = 2
[c] = 1
[fan] = 1
[lie] = 1
[long] = 1
[love] = 1

View Code

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

 

 

 

 

 

    原文作者:Cocoon
    原文地址: https://www.cnblogs.com/CocoonFan/archive/2013/06/07/3123134.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞