我用 C++ 制作了这个非常简单的纸牌。牌组是随机洗牌的,我拿一张牌,然后按 Ace、One、Two、...、Ten、Jack、Queen、King 的顺序发音。如果这张牌正是我所说的,我会从牌组中取出这张牌。我使用剩余的牌组迭代该过程,直到我移除卡片或直到牌组为空(仅在这种情况下我赢了)。这是我编写的代码,但是当我使用功能擦除删除卡时,第 62 行出现错误。我不明白是哪个问题。
#include <iostream>
#include <vector>
using namespace std;
enum SUIT { HEART, CLUB, DIAMOND, SPADE };
string suit_string[] = {"HEART", "CLUB", "DIAMOND", "SPADE"};
enum VALUE { ACE, TWO, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};
string value_string[] = {"ACE", "TWO", "THREE", "FOUR", "FIVE",
"SIX", "SEVEN", "EIGHT","NINE", "TEN", "JACK", "QUEEN", "KING"};
class Card {
public:
Card(SUIT s, VALUE v);
SUIT suit;
VALUE value;
string toString();
};
Card::Card(SUIT s, VALUE v){
suit=s;
value=v;
}
string Card::toString(){
return value_string[(int)this->value]+" of "+suit_string[(int)this->suit];
}
int main() {
vector<Card*> deck;
for (int i=0; i<4; i++) {
for (int j=0; j<13; j++) {
deck.push_back(new Card((SUIT)i,(VALUE)j));
}
}
int removed_count, runs = 0;
do{
random_shuffle(deck.begin(),deck.end());
removed_count=0;
cout<<"--- Run number: "<<++runs<<"\n";
cout<<"--- still "<<deck.size()<<" cards in the deck\n";
for (int i=0; i<4; i++) {
for (int j=0; j<13; j++) {
//cout<<i*13+j<<"\n";
int position=i*13+j; //from 0 to 51
cout<<"'"+value_string[j]+"'"<<" <-> ";
Card card=*(deck.at(position));
cout<<card.toString()<<" ";
if(card.value == j){
removed_count++;
deck.erase(deck.begin()+position); //problems here!
cout<<"removed\n";
}else{
cout<<"not removed\n";
}
}
}
if(deck.empty()) break;
}while(removed_count>0);
if(deck.empty()){
cout<<"You win!\n";
}else{
cout<<"You lose!\n";
}
return 0;
}