映射

来源:互联网 发布:美图秀秀出mac版了吗 编辑:程序博客网 时间:2024/05/04 10:43

映射仅是一个存储键值对的数据结构,以键作为索引。

 

一些语言和库称之为字典(dictionary)或者(association)。映射包括两个部分,一部分存储键,一部分是键出现的次数的值。这正好用来完成单词出现次数的统计程序实现。

 

std::map<std::string ,int> counts;

 

它是通过键值来访问的,如counts["the"]返回the的值

 

EXAMPLE

 

#include <iostream>
#include <istream>
#include <ostream>
#include <map>
#include <string>
#include <iomanip>

int main()
{
 using namespace std;

 map<string,int> counts;
 string word;

 //从标准输入读取单词,并计算每个单词现的次数
 while(cin >> word)
  ++counts[word];

 int longest(0);
 for(map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
 {
  if(iter->first.size() > longest)   //取得单词中最长的一个的长度
   longest = iter->first.size();
 }

 const int count_size(10);

 for(map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
  cout<< setw(longest) << left <<iter->first    //以一定的格式输出
   << "\t"
   << setw(count_size) << right << iter->second << "\n";

}

 

POSSIBLE OUT

 

映射在这样一种程序的设计中必定是一个很好的工具,当然还有很多问题,比如没有考虑大小写的问题,还有标点的情况,还有待改进。

原创粉丝点击