XHAENEUNG 풀기는 풀었는데 찜찜하네요

  • User Avatar
    ais1406

    일단 풀기는 풀었습니다.. 하지만


    ~~~ c++
    char ans[11][10] = {
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "ten"
    };

    char first[10];
    void input()
    {
    scanf("%s", first);
    }

    void process()
    {
    if (!strcmp(first, ans[0]))
    f = 0;
    else if (!strcmp(first, ans[1]))
    f = 1;
    else if (!strcmp(first, ans[2]))
    f = 2;
    else if (!strcmp(first, ans[3]))
    f = 3;
    else if (!strcmp(first, ans[4]))
    f = 4;
    else if (!strcmp(first, ans[5]))
    f = 5;
    else if (!strcmp(first, ans[6]))
    f = 6;
    else if (!strcmp(first, ans[7]))
    f = 7;
    else if (!strcmp(first, ans[8]))
    f = 8;
    else if (!strcmp(first, ans[9]))
    f = 9;
    else if (!strcmp(first, ans[10]))
    f = 10;

    </spoiler>
    
    이렇게 일일히 문자열과 숫자를 대칭시키니 
    코드꼴이 영 좋지않네요 가장확실한 방법인거같지만 
    깔끔한 방법이 있을까요? enum을 써도 어차피 저런식으로 매칭을 해야하는거 아닌가요? 문자열 비교는..
    좋은 방법 추천해주세요
    
    for 로 길이를 줄이는거 말고 다른 '방법' 이 있을까요?
    
    

    10년 전
2개의 댓글이 있습니다.
  • User Avatar
    amok

    c++이라면 map(또는 unordered_map)을 쓰시면 됩니다.
    c++11 에서는 initializer list 를 이용해서 다음과 같이 코딩할 수 있습니다:

    #include <map>
    
    map<string, int> intval ={
        { "zero", 0 },
        { "one", 1 },
        { "two", 2 },
        { "three", 3 },
        { "four", 4 },
        { "five", 5 },
        { "six", 6 },
        { "seven", 7 },
        { "eight", 8 },
        { "nine", 9 },
        { "ten", 10 },
    };
    map<string, int> intval2;
    
    map<string, function<int(int, int)>> f ={
        { "+", [](int a, int b){ return a + b; } },
        { "-", [](int a, int b){ return a - b; } },
        { "*", [](int a, int b){ return a * b; } },
    };
    
    
    ...
    
    cin >> tmp; A = intval[tmp];
    cin >> op;
    cin >> tmp; B = intval[tmp];
    cin >> tmp;
    
    ...
    
    bool ans = f[op](A, B) == C;
    puts(ans ? "Yes" : "No");
    
    

    10년 전 link
  • User Avatar
    ais1406

    감사합니다. python의 dict 같은거네요


    10년 전 link
  • 정회원 권한이 있어야 커멘트를 다실 수 있습니다. 정회원이 되시려면 온라인 저지에서 5문제 이상을 푸시고, 가입 후 7일 이상이 지나셔야 합니다. 현재 문제를 푸셨습니다.