閱讀以下說明和C++代碼,將應填入 (n) 處的字句寫在答題紙的對應欄內(nèi)。
【說明】
C++標準模板庫中提供了map模板類,該模板類可以表示多個“鍵-值”對的集合,其中鍵的作用與普通數(shù)組中的索引相當,而值用作待存儲和檢索的數(shù)據(jù)。此外,C++模板庫還提供了pair模板類,該類可以表示一個“鍵-值”對。pair對象包含兩個屬性:first和second,其中first表示“鍵-值”中的“鍵” ,而second表示“鍵-值”中的“值”。
map 類提供了 insert 方法和 find 方法,用于插入和查找信息。應用時,將一個 pair對象插入(insert)到 map 對象后,根據(jù)“鍵”在 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); //根據(jù)員工編號查找員工信息
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;
}