在hashmap中搜索,其中键可以是单个字符串或空格分隔的字符串
Search in a hashmap where the key can be a single string or space separated strings
我必须创建一个哈希映射,其中键以"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
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何将包含括号的字符串列表平展为单个列表?
- 将字符向量转换为单个字符串
- C++ 字符串单个字符
- 如何在 c++ 中将 2D 数组转换为单个字符串
- 将单个字符串/字符输入串行监视器
- 将字符串中的单个单词替换为另一个单词
- C++ 如何将字符串拆分为单个字符
- 将字符串拆分为单个单词并将它们放置在向量中
- 将C字符串转换为单个整数
- 查找单个字符串中重复次数最多和次数第二多的字符
- 字符串中单个字符作为数组的数据类型是什么
- 字符串中的重音,如何在单个字符中存储重音字符
- 从字符串中提取单个字符并将其转换为 int
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 输入到字符串流并在单个语句中转换为字符串.可以没有帮助程序类
- 如何使用 deleteEntry 函数 c++ 删除数组中的单个字符串
- 反转具有单个循环的字符串
- spdlog 记录单个wchar_t字符串,其中包含包含 {..} 的数据
- 如何从空格分隔的单个字符串中提取多个子字符串