我正在尝试创建一个简单的卡洗牌和处理模拟器。我使用向量来表示一副52张牌,每张牌由结构BitCard
表示,其元素的空间是内存受位域限制。但是当构造函数尝试访问向量时,xCode会抛出BAD_ACCESS exception: Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
。我做了一些研究,发现这个异常与空指针相关联,但似乎无法弄清楚如何修复它。我的代码如下:
#include <iostream>
#include <cctype>
#include <cstdlib>
#include <vector>
#include <iomanip>
using namespace std;
struct BitCard{
unsigned face:4;
unsigned color:1;
unsigned suit:2;
};
class DeckOfCards {
public:
static const int faces = 13;
static const int colors = 2;
static const int numberOfCards = 52;
DeckOfCards();
void shuffle();
void deal();
private:
vector <BitCard> deck={};
};
DeckOfCards::DeckOfCards(){
for (int i = 0; i <numberOfCards;++i){
deck[i].face = i%faces;
deck[i].suit = i/faces;
deck[i].color = i/(faces*colors);
}
}
void DeckOfCards:: shuffle(){
for (int i = 0; i <numberOfCards;i++){
int j = rand()%numberOfCards;
BitCard tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
}
void DeckOfCards:: deal(){
for (int k1 = 0, k2 = k1+numberOfCards/2;k1<numberOfCards/2-1;k1++,k2++)
{
cout << "Color:" << setw(3) << deck[k1].color
<< " Card:" << setw(3) << deck[k1].face
<< " Suit:" << setw(3) << deck[k1].suit
<< " Color:" << setw(3) << deck[k2].color
<< " Card:" << setw(3) << deck[k2].face
<< " Card:" << setw(3) << deck[k2].suit;
}
}
int main(int argc, const char * argv[]) {
DeckOfCards testDeck;
testDeck.shuffle();
testDeck.deal();
return 0;
}
在行
中生成异常deck[i].face = i%faces;
我该如何解决这个问题? 提前谢谢!
答案 0 :(得分:1)
您正尝试在构造函数中访问向量deck
的元素。但是当你调用构造函数时,deck
向量是空的
vector <BitCard> deck={}; // <- empty deck
DeckOfCards::DeckOfCards(){
for (int i = 0; i <numberOfCards;++i){
deck[i].face = i%faces; // <- At construction time, you are trying to access deck with index i. but Deck is empty!
//...
}
}
一种解决方案是构建对象BitCard
并将其推送到vector
DeckOfCards::DeckOfCards(){
for (int i = 0; i <numberOfCards;++i){
BitCard myBitCard;
myBitCard.face = i%faces;
myBitCard.suit = i/faces;
myBitCard.color = i/(faces*colors);
deck.push_back(myBitCard);
}
}
答案 1 :(得分:1)
deck
向量的大小始终为0.使用[]
索引向量不会自动调整向量大小以容纳无效索引。
您可以将其初始化为正确的大小。
vector <BitCard> deck(numberOfCards);
或者在构造函数中调整它的大小。
DeckOfCards::DeckOfCards(){
deck.resize(numberOfCards);
或者你可以在构造函数的循环中使用push_back
将每张新卡添加到向量的末尾。
DeckOfCards::DeckOfCards(){
for (int i = 0; i <numberOfCards;++i){
BitCard card;
card.face = i%faces;
card.suit = i/faces;
card.color = i/(faces*colors);
deck.push_back( card )
}
}