我在自定义排序字符串方面遇到了一些问题。我基本上拥有的是 std::pair
的 std::list
,其元素是 enum class
和 std::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/