在hashmap中搜索,其中键可以是单个字符串或空格分隔的字符串

Search in a hashmap where the key can be a single string or space separated strings

本文关键字:字符串 单个 分隔 空格 搜索 hashmap      更新时间:2023-10-16

我必须创建一个哈希映射,其中键以"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 foundn";
    }
    return 0;
}

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

所以你可以使用这个:

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通常不是整数,因此您可能需要使用字符串来表示phoneNumber