Reputation: 535
i'm trying to implement a cards game and i'm using a vector of cards. I implemented every comparison operator there is with the hope that the 'sort' function will sort according to those operators, but I always get that ace is the smallest card.
I tried sorting manually but it became really ugly.
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);
};
c'tor of card:
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);
}
the sorting part:
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());
operators implementation:
bool Card::operator>(Card &other) {
return this->worth > other.worth;
}
bool Card::operator<(Card &other) {
return this->worth < other.worth;
}
... same for all
I expect a sorted vector of 5 cards to be: 2,3,4,5,1 but the actual vecter is: 1,2,3,4,5.
Upvotes: 2
Views: 199
Reputation: 535
as @Jon Doe wrote
I wrote:
sort(sorted_hand.begin(), sorted_hand.end(), cardCompare);
while:
bool cardCompare(const Card* lh, const Card* rh) {
return *lh <= *rh;
}
Upvotes: 0
Reputation: 206607
I can think of couple of ways to deal with the problem.
Assign the value 14 to ace.
Account for the special nature of the ace in the comparison function.
bool Card::operator<(Card &other) {
int l = (this->worth == 1) ? 14 : this->worth;
int r = (other.worth == 1) ? 14 : other.worth;
return (l < r);
}
Change the function to work with const
objects.
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);
}
Upvotes: 3