c++ - 在 C++ 中自定义排序字符串

标签 c++ list sorting

我在自定义排序字符串方面遇到了一些问题。我基本上拥有的是 std::pairstd::list,其元素是 enum classstd::string Enum 用于颜色(正确排序的颜色),strings 包含 [2, 10] 区间内的数字,分别添加字母 J、Q、K 和 A。你可能已经猜到了,这是一副纸牌,排序后一定是这样的: 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A.

为了实现这一目标,我的 lambda 函数应该是什么样子?还是有别的办法?

这是我目前为止的表现:

enum class Colours
{
Spades, Clubs, Hearts, Diamonds
};

typedef std::list<std::pair<Colours, std::string>> Deck;
typedef std::pair<Boje, std::string> Pair;

这是实际的排序:

deck.sort( [] (const Pair &x, const Pair &y) -> bool {
        if(x.first == y.first) return x.second < y.second;
        else return x.first < y.first;
    } );

而当前排序结果:10 2 3 4 5 6 7 8 9 A J K Q

最佳答案

您要做的一件事是每个 string 的第一个字符都是唯一的。此代码未经测试,但应该接近:

unsigned int face_value(std::string const &face) {
    if(std::isdigit(face[0])) {
        // if the length is 1 we just need the digit
        if(face.length() == 1) {
            return face[0] - '0';
        }
        // if it's not 1, it has to be 10
        return 10;
    }
    switch(face[0]) {
    case 'J':
        return 11;
        break;

    case 'Q':
        return 12;
        break;

    case 'K':
        return 13;
        break;

    case 'A':
        return 14;
        break;

    default:
        assert(false);
        break;
    }
}

bool face_compare(std::string const &first, std::string const &second) {
    return face_value(first) < face_value(second);
}

有了辅助函数,lambda 就很简单了:

deck.sort( [] (const Pair &x, const Pair &y) -> bool {
    return std::tie(x.first, face_value(x.second)) <
           std::tie(y.first, face_value(y.second));
});

作为旁注,我的猜测是您想在 Colour 之前比较面值,但我现在坚持您的原始逻辑。

关于c++ - 在 C++ 中自定义排序字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50366984/

相关文章:

c++ - 当 Lua 绑定(bind)在该类中时,使用 LuaBind 在该类中调用 Lua 函数

Java 泛型返回类型语法

java - 需要对字符串值进行排序,同时忽略对空字符串值的任何位置更改

PHP/MySql 排序问题

python-3.x - 为什么我的合并排序算法不起作用?

c++ - 遍历 map<string, string> 并使用 SDL_TTF 绘制其内容时出现段错误

c++ - 从长远来看,使用调试器和大量使用 C++ 模板是否不兼容?

c++ - 新的 C++ Mongo 驱动程序 : how to see type and how to get string value

python - 如何通过应用 numpy 向量化使用条件检查从 python 列表或 numpy 数组中提取值?

python - 从 n 个相等的项目中挑选与最小数字相关的项目