简单的代码行

Dah*_*heh 2 c++

此代码用于列出字符串(Kh,6c,5h等)中的卡牌组(从51开始为0),反之亦然.

我已为它编写代码,但似乎很长.有没有更有效的方式来写这个?

我也想这样做,将一个字符串发送到一个函数并得到一个int.

std::string Card::getString(int card) {
    std::string cardstring;

    switch (card) {

    case 0:
        return "2c";
    case 1:
        return "3c";
    case 2:
        return "4c";
    case 3:
        return "5c";
    case 4:
        return "6c";
    case 5:
        return "7c";
    case 6:
        return "8c";
    case 7:
        return "9c";
    case 8:
        return "Tc";
    case 9:
        return "Jc";
    case 10:
        return "Qc";
    case 11:
        return "Kc";
    case 12:
        return "Ac";
    case 13:
        return "2d";
    case 14:
        return "3d";
    case 15:
        return "4d";
    case 16:
        return "5d";
    case 17:
        return "6d";
    case 18:
        return "7d";
    case 19:
        return "8d";
    case 20:
        return "9d";
    case 21:
        return "Td";
    case 22:
        return "Jd";
    case 23:
        return "Qd";
    case 24:
        return "Kd";
    case 25:
        return "Ad";
    case 26:
        return "2h";
    case 27:
        return "3h";
    case 28:
        return "4h";
    case 29:
        return "5h";
    case 30:
        return "6h";
    case 31:
        return "7h";
    case 32:
        return "8h";
    case 33:
        return "9h";
    case 34:
        return "Th";
    case 35:
        return "Jh";
    case 36:
        return "Qh";
    case 37:
        return "Kh";
    case 38:
        return "Ah";
    case 39:
        return "2s";
    case 40:
        return "3s";
    case 41:
        return "4s";
    case 42:
        return "5s";
    case 43:
        return "6s";
    case 44:
        return "7s";
    case 45:
        return "8s";
    case 46:
        return "9s";
    case 47:
        return "Ts";
    case 48:
        return "Js";
    case 49:
        return "Qs";
    case 50:
        return "Ks";
    case 51:
        return "As";
    }
    return cardstring;}
Run Code Online (Sandbox Code Playgroud)

谢谢

Ben*_*ley 17

std::string get_card_string(int card)
{
    if (card >= 0 && card < 52)
    {
        std::string s(2,' ');
        s[0] = "23456789TJQKA"[card % 13];
        s[1] = "cdhs"[card / 13];
        return s;
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)

相反的过程有点复杂.如果我想了一会儿,我可能想出一个更聪明的方法,但显而易见的选择是这样的:

std::unordered_map<std::string, int> initialize_card_map()
{
    std::unordered_map<std::string, int> m;
    for (int i=0; i<52; ++i)
        m[get_card_string(i)] = i;
    return m;
}

int get_card_number(std::string const & card_string)
{
    static std::unordered_map<std::string, int> const m = initialize_card_map();
    auto it = m.find(card_string);
    if (it != m.end())
        return it->second;

    return ??? value not found
}
Run Code Online (Sandbox Code Playgroud)