1 분 소요

기존 코드

#include <string>
#include <vector>
#include <map>
#include <sstream>

using namespace std;

vector<string> solution(vector<string> record) {
    vector<string> answer;

    vector<vector <string>>order;

    for(string cur : record){
        istringstream ss(cur);
        string buffer = "";
        vector <string> save;
        while (getline(ss, buffer, ' ')){
            save.push_back(buffer);
        }
        order.push_back(save);
    }

    map <string, string> chat; //uid, 닉네임
    for(vector <string> cur : order){
        string act = cur[0];
        string uid = cur[1];
        string nickname = cur[2];

        if(act == "Enter"){
            if(chat[uid] == nickname) continue; //이미 존재
            chat[uid] = nickname;
        }else if(act == "Change"){
            chat[uid] = nickname;
        }
    }

    for(vector <string> cur : order){
        string act = cur[0];
        string uid = cur[1];

        if(act == "Enter"){
            answer.push_back(chat[uid] + "님이 들어왔습니다.");
        }else if(act == "Leave"){ //leave
            answer.push_back(chat[uid] + "님이 나갔습니다.");
        }
    }
    return answer;
}

C++ exception with description “basic_string::_M_construct null not valid” thrown in the test body.

  • 이런 오류가 났음..
  • 벡터 iterating 하는 부분에서 오류가 생겼다.
  • 구글링 해보니 dangaling reference 때문이라고 한다.
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>
using namespace std;
vector<string> solution(vector<string> record)
{
    vector<string> answer;

    vector<vector<string>> orders;

    for (string cur : record)
    {
        istringstream ss(cur);
        string buffer = "";
        vector<string> save;
        while (getline(ss, buffer, ' '))
            save.push_back(buffer);
            
        orders.push_back(save);
    }

    map<string, string> chat; //uid, 닉네임

    for (vector <string> order : orders)
    {
        if (order[0] == "Enter" || order[0] == "Change")
            chat[order[1]] = order[2];
    }

    for (vector<string> order : orders)
    {
        string act = order[0];
        string uid = order[1];

        if (act == "Enter")
            answer.push_back(chat[uid] + "님이 들어왔습니다.");
        else if (act == "Leave")
            answer.push_back(chat[uid] + "님이 나갔습니다.");
    }

    return answer;
}
int main()
{
    vector<string> ans = solution({"Enter uid1234 Muzi",
                                   "Enter uid4567 Prodo", "Leave uid1234", "Enter uid1234 Prodo", "Change uid4567 Ryan"});

    for (auto c : ans)
    {
        cout << c << endl;
    }
    return 0;
}
  • 바꾼 코드. 잘 돌아간다.

카테고리:

업데이트: