[英]I tried to use map in problem but it seems wrong i can t find problem. Could you help me?
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
map<string,string> mym;
int n;
string s,a,r;
cin >> n;
for(int i=0; i<n; i++){
getline(cin,s);
getline(cin,a);
mym.insert(pair<string,string>(s,a));
s.erase();
a.erase();
}
for(int i=0; i<n; i++){
getline(cin,r);
if(mym.count(r)!=0){
cout << r << '=' << mym.at(r) <<endl;
}
else cout << "Not found" << endl;
r.clear();
}
return 0;
}
https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
sam 99912222 tom 11122222 harry 12299933 sam edward harry山姆 99912222 汤姆 11122222 哈利 12299933 山姆·爱德华·哈利
Not found =sam 99912222 =sam 99912222未找到 =sam 99912222 =sam 99912222
This line:这一行:
cin >> n;辛 >> n;
Will consume the number of the input, but won't consume the subsequent end of line that follows before the next string.将消耗输入的数量,但不会消耗下一个字符串之前的后续行尾。
So instead of cin >> n
, do this:所以代替cin >> n
,这样做:
string tmp;
getline(cin, tmp);
n = atoi(tmp.c_str());
There's probably other ways to do this.可能还有其他方法可以做到这一点。
Some other code cleanup as follows:其他一些代码清理如下:
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
map<string,string> mym;
int n;
string tmp;
cin >> tmp;
n = atoi(tmp.c_str());
for(int i=0; i<n; i++) {
string s, a;
getline(cin,s);
getline(cin,a);
mym[s] = a;
}
for(int i=0; i<n; i++) {
string r;
getline(cin,r);
auto itor = mym.find(r);
if(itor != mym.end())
cout << r << '=' << itor->second <<endl;
}
else {
cout << "Not found" << endl;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.