阅读以下说明和C++代码,将应填入 (n) 处的字句写在答题纸的对应栏内。
【说明】
C++标准模板库中提供了map模板类,该模板类可以表示多个“键-值”对的集合,其中键的作用与普通数组中的索引相当,而值用作待存储和检索的数据。此外,C++模板库还提供了pair模板类,该类可以表示一个“键-值”对。pair对象包含两个属性:first和second,其中first表示“键-值”中的“键” ,而second表示“键-值”中的“值”。
map 类提供了 insert 方法和 find 方法,用于插入和查找信息。应用时,将一个 pair对象插入(insert)到 map 对象后,根据“键”在 map 对象中进行查找(find),即可获得一个指向pair对象的迭代器。
下面的 C++代码中使用了 map和 pair 模板类,将编号为 1001、1002、1003 的员工信息插入到map对象中,然后输入一个指定的员工编号,通过员工编号来获取员工的基本信息。员工编号为整型编码,员工的基本信息定义为类employee。
map对象与员工对象之间的关系及存储结构如图5-1所示。
【C++代码】
#include <iostream>
#include <map>
#include <string>
using namespace std ;
class employee{
(1) :
employee(string name,string phoneNumber, string address){
this->name = name;
this->phoneNumber = phoneNumber;
this->address = address;
}
string name;
string phoneNumber;
string address;
};
int main( )
{
map <int, employee*> employeeMap;
typedef pair <int, employee*> employeePair;
for (int employIndex = 1001; employIndex <= 1003; employIndex++){
char temp[10] ; //临时存储空间
_itoa(employIndex,temp,10); //将employIndex转化为字符串存储在temp中
string tmp( (2) ); //通过temp构造string对象
employeeMap. (3) ( employeePair ( employIndex,
new employee("employee-" + tmp,
"85523927-"+tmp,
"address-"+tmp)
)
); //将员工编号和员工信息插入到employeeMap对象中
}
int employeeNo = 0;
cout << "请输入员工编号:";
(4) >> employeeNo; //从标准输入获得员工编号
map<int,employee*>::const_iterator it;
it = (5) .find(employeeNo); //根据员工编号查找员工信息
if (it == employeeMap.end()) {
cout << "该员工编号不存在 !" << endl;
return -1;
}
cout << "你所查询的员工编号为:" << it->first << endl;
cout << "该员工姓名:" << it->second->name << endl;
cout << "该员工电话:" << it->second->phoneNumber << endl;
cout << "该员工地址:" << it->second->address << endl;
return 0;
}