gpt4 book ai didi

c++ - 我正在努力处理二维数组参数

转载 作者:行者123 更新时间:2023-11-30 02:14:01 25 4
gpt4 key购买 nike

我必须让用户定义的函数随机化二维矩阵的值,并让另一个用户定义的函数打印出来。我在参数方面遇到问题,其他地方都给我令人困惑/相反的答案。

我试过了

-int antcolony[SIZE][SIZE]
-int antcolony[][SIZE]
-int antcolony[][]
-int antcolony[SIZE,SIZE]

还有其他的我想不起来了。请帮忙

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

/* Function: colonizePhermones
* Parameters: int Size, const int antColony[][SIZE]
* Return: n/a
* Description: randomize the values in antColony
*/
void colonizePhermones(int SIZE, int antColony[SIZE][SIZE]);

/* Function: printPhermones
* Parameters: const int antColony[][SIZE]
* Return: n/a
* Description: print the values in antColony
*/
void printPhermones(int SIZE, int antColony[SIZE][SIZE]);


int main() {
//declaring variables
const int SIZE = 10;
int colonyPath[SIZE];
int antColony[SIZE][SIZE];
int pathCounter = 0;
colonyPath[pathCounter]= 0;

//test caling functions
colonizePhermones(SIZE, antColony[SIZE][SIZE]);
printPhermones(SIZE, antColony[SIZE][SIZE]);

return 0;
}

void colonizePhermones(int SIZE, int antColony[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if ( i == j) {
antColony[i][j] = 0;
}
else {
antColony[i][j] = ((rand() % 19) +1);
}
}
}
}

void printPhermones(int SIZE, int antColony[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
cout << antColony[i][j] << " ";
}
cout << endl;
}
}

除了给我错误信息,它什么都不做。我需要它来打印数组。

最佳答案

附加信息:

如果您想将一个普通的旧 C 数组传递给一个函数,您有 2 种可能性。

  1. 通过引用传递
  2. 通过指针传递

看来你是想按引用传递。但是你使用了错误的语法。

请看:

void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4]) // For passing array by pointer
{}

int main()
{
int matrix[3][4]; // Define 2 dimensional array

function1(matrix); // Call by reference
function2(&matrix); // Call via pointer
return 0;
}

您传递给函数的是指向 int 数组的衰减指针。

只需更正语法即可。

附加提示:

不要在 C++ 中使用普通的 C 风格数组。绝不。请使用STL容器。

关于c++ - 我正在努力处理二维数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584057/

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