[프로그래머스 C++] 오픈채팅방

 

https://school.programmers.co.kr/learn/courses/30/lessons/42888

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


 

해결전략

 

문자열

map

sstream, stringstream   -->>  사용하려면 #include<sstream> 을 선언해야 한다.

 

 


 

코드

 

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

map<string, string> idNname;        // ID와 닉네임을 등록하는 map
vector<pair<string, string>> index; // 입장과 퇴장을 기록하는 배열

vector<string> solution(vector<string> record) {
    vector<string> answer;
        
    for(int i=0; i<record.size(); i++)
    {
        stringstream ss(record[i]);
        string command, id, name;   
        ss >> command >> id >> name; // 빈칸 기준으로 자른 문자열을 각각 기록

        if(command == "Enter")
        {
            if(id != "") // 이전에 들어갔다 나간 후 다시 들어온 경우
                idNname[id] = name;
            else // 처음 들어온 경우
                idNname.insert({id, name });

            index.push_back({ command, id });
        }
        else if (command == "Leave") 
        {
            index.push_back({ command, id });
        }
        else if (command == "Change") 
        {
            idNname[id] = name;
        }	           
    }

    for (int i =0; i<index.size(); i++)
    {
    	// index[].first에 기록한 command를 사용하여 어떤 문구가 나올지 결정한다. 
    	// index[].second에 기록한 id를 사용하여 idNname의 닉네임을 찾아서 사용한다.
        if (index[i].first == "Enter"){
            answer.push_back(idNname[index[i].second] + "님이 들어왔습니다.");
        }
        else if (index[i].first == "Leave"){
            answer.push_back(idNname[index[i].second] + "님이 나갔습니다.");
        }        
    }
    
    return answer;
}

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

    solution(testcase1);

    return 0;
}