C++编程思想 第2卷 第7章 通用容器 关联式容器 不可思议的映像

一个普通的数组使用一个整数值来对连续排列的某种类型的元素集进行索引
map是一个关联式数组  associative array
按照类数组的方式将一个对象与另一个对象关联到一起

//: C07:WordCount.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Count occurrences of words using a map.
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include "../require.h"
using namespace std;

int main(int argc, char* argv[]) {
  typedef map<string, int> WordMap;
  typedef WordMap::iterator WMIter;
  const char* fname = "WordCount.cpp";
  if(argc > 1) fname = argv[1];
  ifstream in(fname);
  assure(in, fname);
  WordMap wordmap;
  string word;
  while(in >> word)
    wordmap[word]++;
  for(WMIter w = wordmap.begin(); w != wordmap.end(); w++)
    cout << w->first << ": " << w->second << endl;
  getchar();
} ///:~


输出
!=: 1
": 1
"../require.h": 1
":: 1
"Thinking: 1
"WordCount.cpp";: 1
#include: 5
&: 1
'License.txt',: 1
(c): 1
//: 5
///:~: 1
//:: 1
1): 1
1995-2004: 1
2",: 1
<<: 4
<fstream>: 1
<iostream>: 1
<map>: 1
<string>: 1
=: 3
>: 1
>>: 1
All: 1
Allison.: 1
Bruce: 1
C++,: 1
C07:WordCount.cpp: 1
Chuck: 1
Count: 1
Eckel: 1
From: 1
Inc.: 1
MindView,: 1
Reserved.: 1
Rights: 1
See: 1
Volume: 1
WMIter;: 1
WordMap: 1
WordMap::iterator: 1
WordMap;: 1
a: 1
argc,: 1
argv[1];: 1
argv[]): 1
assure(in,: 1
at: 1
available: 1
by: 1
char*: 2
code: 2
const: 1
cout: 1
distributed: 1
endl;: 1
file: 1
fname: 2
fname);: 1
for(WMIter: 1
getchar();: 1
if(argc: 1
ifstream: 1
in: 2
in(fname);: 1
int: 1
int>: 1
main(int: 1
map.: 1
map<string,: 1
namespace: 1
occurrences: 1
of: 1
package: 1
permissions: 1
source: 1
stated: 1
std;: 1
string: 1
the: 2
typedef: 2
use: 1
using: 2
w: 2
w++): 1
w->first: 1
w->second: 1
while(in: 1
with: 1
word): 1
word;: 1
wordmap.begin();: 1
wordmap.end();: 1
wordmap;: 1
wordmap[word]++;: 1
words: 1
www.MindView.net.: 1
{: 1
}: 1

如果map映像中没有这样一个单词
则作为该单词的关键字-值 对就会自动插入到map映像中
并调用返回值为0的伪构造函数int()并将其初始化为0

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/82531830