当前位置: 首页 > 图文教程 > 开发语言 > VC++ > 使用 <map> 库创建关联容器
| 使用 <map> 库创建关联容器 下载源代码
关系数据库,科学计算应用以及基于Web的系统常常需要类似 vector 的容器,其索引可以是如何数据类型,不一定是整数。这样的容器叫关联容器,或者 map。例如,目录服务应用可以将私人姓名作为索引来存储,电话号码作为其关联的值: directory["Harry"]=8225687;// 插入 "Harry" 并与他的电话号码关联iterator it=directory.find("Harry");// 获取 Harry 的电话号码 其它关联容器的应用还包括将 URLs 映射到 IP 的 DNS 服务器,字典,库存清单,工资表等等。那么如何突破整型索引的局限,实现用其它数据类型作为索引的关联容器呢?答案是:使用 <map> 库创建和处理关联容器。 #include <utility> //definition of pair#include <string>pair <string, string> prof_and_course("Jones", "Syntax");pair <int, string> symbolic_const (0, "false"); 标准库还定义了一个辅助函数,方便 pair 类型的创建: string prof;string course;make_pair(prof,course);//returns pair <string,string> 第一步:构造和初始化一个 map 对象 #include <map>map <string, string> addresses; 为了添加元素,使用下标算符: addresses["Paul W."]="[email protected]"; 这里,串“Paul W.”是索引或键值,“[email protected]”是其关联的值。如果该 map 已经包含了此键值,那么当前所关联的值不会改变: addresses["Paul W."]="[email protected]"; // 不起作用 第二步:搜索 iterator find(const key_type& k);const_iterator find(const key_type& k) const; 通常,用 typedef 可以使代码更可读一些: typedef map <string, string>::const_iterator CIT;CIT cit=addresses.find("Paul W.");if (cit==addresses.end()) cout << "sorry, no such key" << endl;else cout << cit->first << ''\t'' << cit->second << endl; 表达式中 cit->first 和 cit->second 分别返回键值及其关联的值。 Bob 35Bob 90Jane 80.25Sue 100Jane 65.5 你的应用程序必须汇总所有代理的奖金并将每个代理的奖金总数显示出来.首先,创建一个 map,然后读取该数据文件: map <string, double> bonuses;string agent;double bonus=0;ifstream bonusfile("bonuses.dat");if(!bonusfile){ // 报告 |