#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
sam 99912222 tom 11122222 harry 12299933 sam edward harry
Not found =sam 99912222 =sam 99912222
This line:
cin >> 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:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.