【问题标题】:Search in a hashmap where the key can be a single string or space separated strings在哈希图中搜索,其中键可以是单个字符串或空格分隔的字符串
【发布时间】: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 以及电话号码不一定是有效整数。

标签: c++ string stl hashmap


【解决方案1】:

很明显,你只需要检查第二个输入是否为整数。

所以你可以使用这个:

string buf, firstName, secondName;
int phone;
cin >> fistName >> secondName;
bool isPhone = 1;
for (auto i: secondName) if (i < '0' || i > '9') {
    isPhone = 0; break;
}
if (!isPhone) {
    cin >> phone;
} else {
    stringstream ss; ss << secondName;
    ss >> phone; secondName = "";
}

请注意,phoneNumbers 不是整数是很常见的,因此您可能希望对 phoneNumbers 使用字符串。

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 2015-01-15
    • 2010-12-01
    • 1970-01-01
    • 2014-07-29
    • 2014-08-11
    • 2013-10-04
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多