gpt4 book ai didi

c++ - 无法使用函数更改数组中的元素

转载 作者:行者123 更新时间:2023-11-28 04:30:46 25 4
gpt4 key购买 nike

我一直在为学校开发一个扑克游戏项目。我有随机生成卡片的代码,但我在使用函数对它们进行排序时遇到了问题。我相信算法本身有效,但我不确定如何正确访问数组中的变量。 Visual Studio 给我错误 argument of type "int (*)[5] is incompatible with parameter of type int *(*)[5] and ' void sortPokerHand(int *[][5])':无法将参数 1 从“int [2][5]”转换为“int *[][5]”

在 main() 中声明 pokerHand

int pokerHand[2][5];

我的职能

//swap the two values
void swap(int* pokerHand, int* x, int* y)
{
int tempVal = pokerHand[0][x];
int tempSuit = pokerHand[1][x];
pokerHand[0][x] = pokerHand[0][y];
pokerHand[1][x] = pokerHand[1][y];
pokerHand[0][y] = tempVal;
pokerHand[1][y] = tempSuit;
}

void sortPokerHand(int* pokerHand[2][5])
{
//bubble sort poker hand
bool swapped;
for (int i = 0; i < 4; i++)
{
swapped = false;
for (int j = 0; j < (5 - i - 1); j++)
{
if (pokerHand[0][j] > pokerHand[0][j + 1])
{
swap(pokerHand[2][5], pokerHand[0][j], pokerHand[0][j + 1]);
swapped = true;
}
}

// If no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}

我是如何尝试使用这个函数的

sortPokerHand(pokerHand);

感谢您的帮助

最佳答案

你做的比它应该做的要难得多。考虑以下先决条件:

  • “手”是五个 int 值的序列
  • 只有单手牌会相对于彼此排序。

鉴于此,您的 swap 例程是完全错误的。它应该通过地址获取两个 int(因此,指向 int 的指针),并使用它们来交换内容:

void swapInt(int *left, int *right)
{
int tmp = *left;
*left = *right;
*right = tmp;
}

接下来,在排序时,我们将单手排序。这意味着五个 int单个序列。因此,不需要传递数组的数组、指向数组的指针、指针的数组或任何类似的东西。只需这样做,干净而基本:

// assumption: a hand has five cards
void sortPokerHand(int hand[])
{
// bubble sort sequence of int
size_t len = 5;
bool swapped = true;
while (swapped && len-- > 0)
{
swapped = false;
for (size_t i = 0; i < len; ++i)
{
if (hand[i] > hand[i + 1])
{
swapInt(hand + i, hand + i + 1); // note: uses our new swap function
swapped = true;
}
}
}
}

最后,我们需要一些手,都需要排序。为了这个示例,我在 main() 中将它们声明为数组的内联数组,然后进行两次调用以实际对它们进行排序,一次一个。然而,首先,我们需要一个打印函数:

void printHand(const int hand[])
{
fputc('{', stdout);
for (size_t i = 0; i < 5; ++i)
printf("%d ", hand[i]);
puts("}");
}

很简单。现在 main()

int main()
{
int hands[2][5] =
{
{ 5,10,7,4,1 },
{ 3,6,8,2,9 }
};

for (size_t i = 0; i < 2; ++i)
{
sortPokerHand(hands[i]);
printHand(hands[i]);
}

return EXIT_SUCCESS;
}

这个程序的输出是:

{1 4 5 7 10 }
{2 3 6 8 9 }

正如我们所料。

就是这样。在更一般的解决方案中,我们将有一个任意大小的手,必须通过排序和打印功能来波及它,以确保完整和正确的事件。知道它的静态尺寸为 5 会让这更容易一些。

另请注意,您可以完全更改 hands 的定义以使用指向数组的指针而不是数组的数组,甚至是指向指针的指针,它仍然可以工作,只要sortHand 和/或 printHand 是指向五个 int 值的 int*

关于c++ - 无法使用函数更改数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com