【发布时间】:2016-04-15 18:44:44
【问题描述】:
我必须创建一个带有键的哈希图,以“firstname lastname”或“firstname”格式存储,并且值是一个整数。然后我必须在收到输入后执行搜索操作直到文件末尾。请建议在我的程序中进行编辑以处理空格分隔的字符串,并在您看到任何其他错误时指出。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
int main() {
long n;
map<string,int> m;
cin>>n;
for(long i=0;i<n;i++){
string name;
int phone;
cin>>name;
cin>>phone;
m.insert(pair<string,int>(name,phone));
}
string query;
while(cin>>query){
map<string,int>::iterator p;
p=m.find(query);
if(p!=m.end())
cout<<p->first<<"="<<p->second<<"\n";
else
cout<<"Not found\n";
}
return 0;
}
【问题讨论】:
-
要读入包含空格的字符串,您将不得不使用
std::getline。我还建议您将电话号码存储为std::string以及电话号码不一定是有效整数。