簡體   English   中英

我嘗試在問題中使用 map 但似乎錯誤我找不到問題。 你可以幫幫我嗎?

[英]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;
}

我嘗試在問題中使用 map 但似乎錯誤我找不到問題。 你可以幫幫我嗎?

https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem

輸入

山姆 99912222 湯姆 11122222 哈利 12299933 山姆·愛德華·哈利

我的結果

未找到 =sam 99912222 =sam 99912222

這一行:

辛 >> n;

將消耗輸入的數量,但不會消耗下一個字符串之前的后續行尾。

所以代替cin >> n ,這樣做:

string tmp;
getline(cin, tmp);
n = atoi(tmp.c_str());

可能還有其他方法可以做到這一點。

其他一些代碼清理如下:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM