尝试使用比较运算符对对象向量进行排序
trying to sort a vector of objects with a comparison operators
我正在尝试实现一个纸牌游戏,我正在使用一个纸牌向量。我实现了每一个比较运算符,希望"排序"函数能根据这些运算符进行排序,但我总是知道王牌是最小的牌。
我试着手动排序,但它变得很难看。
class Card {
int worth;
int num;
Shapes shape_id;
string name;
string shape_name;
string color;
char symbol;
string intToShape(int n);
string intToColor(int n);
public:
Card(int n, int shap);
Card();
int getNumOfCard() const;
int getShapeOfCard() const;
friend std::ostream& operator<<(std::ostream& os, const Card& c);
bool operator >(Card& other);
bool operator <(Card& other);
bool operator ==(Card& other);
bool operator >=(Card& other);
bool operator <=(Card& other);
bool operator !=(Card& other);
};
卡片名称:
Card::Card(int n, int shap) : num(n) , shape_id((Shapes)shap) {
if (num>10 || num ==1) {
switch (num) {
case 11:
name = "Jack" + intToShape(shap);
symbol ='J';
break;
case 12:
name = "Quin" + intToShape(shap);
symbol = 'Q';
break;
case 13:
name = "King" + intToShape(shap);
symbol = 'K';
break;
case 1:
name = "Ace" + intToShape(shap);
symbol = 'A';
break;
default:
string exceptionMessage("num > 13");
throw (PckErr(exceptionMessage));
}
} else {
symbol = 'N';
name = std::to_string(num) + intToShape(shap);
}
if (num == 1) {
worth = 14; //ace worth 14!
} else {
worth = num;
}
shape = intToShape(shap);
color = intToColor(shap);
}
分拣部分:
for (int i = 0; i < 12; ++i) {
histogram[pCard[i]->getNumOfCard()]++;
it = sorted_hand.insert(it,pCard[i]);
}
std::sort(sorted_hand.begin(), sorted_hand.end());
操作员实现:
bool Card::operator>(Card &other) {
return this->worth > other.worth;
}
bool Card::operator<(Card &other) {
return this->worth < other.worth;
}
... same for all
我预计5张牌的排序向量为:2,3,4,5,1但实际矢量是:1,2,3,4,5.
我可以想出几种方法来处理这个问题。
解决方案1
将值14指定给ace。
解决方案2
在比较函数中说明ace的特殊性质。
bool Card::operator<(Card &other) {
int l = (this->worth == 1) ? 14 : this->worth;
int r = (other.worth == 1) ? 14 : other.worth;
return (l < r);
}
清理建议
更改函数以使用const
对象。
bool Card::operator<(Card const& other) const {
int l = (this->worth == 1) ? 14 : this->worth;
int r = (other.worth == 1) ? 14 : other.worth;
return (l < r);
}
@Jon Doe编写
我写道:
sort(sorted_hand.begin(), sorted_hand.end(), cardCompare);
而:
bool cardCompare(const Card* lh, const Card* rh) {
return *lh <= *rh;
}
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 迭代时从向量和内存中删除对象
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 如何创建从同一类继承的不同对象的向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 从多个源构造一个对象,包括一个对象向量
- 在C 中,是否有可能在不兼容类型的std ::向量对象之间传输不同类型的缓冲区
- 将向量对象存储在共享指针投掷错误中
- E0312,C2664尝试将向量对象作为函数参数传递时错误
- 相对于向量对象的两个成员,找到两个向量的相交的有效方法
- 将数据从文件读取到向量对象
- C 向量对象访问
- 向量对象声明后的括号是什么意思
- 2向量对象指向相同的分配内存
- 如何返回向量对象
- 传递单个或向量对象时没有重载函数的实例
- 指向数组和向量对象的指针
- 向量对象库,可以存储其他对象类型的对象
- 如何从另一个向量/对象集构造新的向量/指针集