用C ++重新排列数组中的对象

时间:2021-12-05 21:17:35

I'm making a card shuffling function for the card game. I created an array of Card objects. Then I tried to rearrange the objects in the array using random_shuffle. But it doesn't work.

我正在为纸牌游戏制作纸牌洗牌功能。我创建了一个Card对象数组。然后我尝试使用random_shuffle重新排列数组中的对象。但它不起作用。

char faces[13] = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };
char suits[4] = { char(3), char(4), char(5), char(6) };
int values[13] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11 };

Card** deck = new Card*[52];

for (int row = 0; row <= 3; row++)
{
    for (int column = 0; column <= 12; column++)
    {
        deck[Card::getCounter()] = new Card(suits[row], faces[column], values[column], true);
    }
}
int size = sizeof(deck) / sizeof(deck[0]);
random_shuffle(*deck, *deck + size);

I mean, if I check with cout, like

我的意思是,如果我和cout一起检查,就像

 cout << deck[0]->getFace()<< deck[0]->getSuit() << endl;

it shows 2(heart), like it was before using random_shuffle

它显示2(心脏),就像使用random_shuffle之前一样

1 个解决方案

#1


The problem with your code is that operator size returns the size of a pointer (8 on a 64-bit machine) rather than the size of the array it points to. As a consequence, the expression

代码的问题是运算符大小返回指针的大小(64位机器上的8)而不是它指向的数组的大小。结果,表达

  sizeof(deck) / sizeof(deck[0])

returns 1, and you only shuffle a single value, which means you don't shuffle. The solution can be:

返回1,你只需要洗牌一个值,这意味着你不会随机播放。解决方案可以是:

  1. use the explicit size of the array random_shuffle(*deck, *deck + 52);
  2. 使用数组random_shuffle的显式大小(* deck,* deck + 52);

  3. Better, define

    const int NUM_OF_CARD_IN_DECK= 52

    const int NUM_OF_CARD_IN_DECK = 52

and use it anywhere you need it

并在任何需要的地方使用它

  1. Better still, use an std::vector
  2. 更好的是,使用std :: vector

#1


The problem with your code is that operator size returns the size of a pointer (8 on a 64-bit machine) rather than the size of the array it points to. As a consequence, the expression

代码的问题是运算符大小返回指针的大小(64位机器上的8)而不是它指向的数组的大小。结果,表达

  sizeof(deck) / sizeof(deck[0])

returns 1, and you only shuffle a single value, which means you don't shuffle. The solution can be:

返回1,你只需要洗牌一个值,这意味着你不会随机播放。解决方案可以是:

  1. use the explicit size of the array random_shuffle(*deck, *deck + 52);
  2. 使用数组random_shuffle的显式大小(* deck,* deck + 52);

  3. Better, define

    const int NUM_OF_CARD_IN_DECK= 52

    const int NUM_OF_CARD_IN_DECK = 52

and use it anywhere you need it

并在任何需要的地方使用它

  1. Better still, use an std::vector
  2. 更好的是,使用std :: vector