获取动态二维数组元素的行/列

发布于 2024-12-18 23:18:19 字数 480 浏览 1 评论 0原文

我目前正在使用以下代码来获取 2D int 数组中元素的当前行和列:

const int num_rows = 5;
const int num_columns = 7;

int a[num_rows][num_columns];

int *p = &a[2][4];

int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);

这工作正常,但现在我需要更改代码以将行数和列数作为参数。据我所知,这意味着我需要动态创建 2D 数组:

int** ary = new int*[sizeX]; 

for(int i = 0; i < sizeX; ++i) 
    ary[i] = new int[sizeY]; 

如果我以这种方式创建 2D 数组,上面查找行/列的代码就会中断。我能做些什么?

I am currently using the following code to get the current row and column of an element in a 2D int array:

const int num_rows = 5;
const int num_columns = 7;

int a[num_rows][num_columns];

int *p = &a[2][4];

int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);

This works fine but now I need to change the code to take the number of rows and columns as a parameter. As far as I know, this means I need to create the 2D array dynamically:

int** ary = new int*[sizeX]; 

for(int i = 0; i < sizeX; ++i) 
    ary[i] = new int[sizeY]; 

If I create the 2D array this way, the above code to find the row/column breaks. What can I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我闹别瞎闹 2024-12-25 23:18:20
 int *ary = new int [sizeX * sizeY]; // allocate memory for the 2d array

 for(int i = 0; i < sizeX; ++I)
     for(j = 0; j < sizeY; ++j) 
          ary[i * sizeY + j] = 0;

  // to get the value of collumn c and row r: use ary[c * sizeY + r];
 int *ary = new int [sizeX * sizeY]; // allocate memory for the 2d array

 for(int i = 0; i < sizeX; ++I)
     for(j = 0; j < sizeY; ++j) 
          ary[i * sizeY + j] = 0;

  // to get the value of collumn c and row r: use ary[c * sizeY + r];
我一向站在原地 2024-12-25 23:18:20
int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[行][0]);

远离指针算术是一个非常好的主意。不要这样做!您本质上是减去指针并将该数字除以 num_columns,该数字将是随机的。

如果要获取某个元素的行/列,请一次搜索数组中的一个元素。

for(int row=0; row<num_rows; ++row) {
   for(int column=0; column<num_columns; ++column) {
      if (a[row][column] == element) {
         // we got it!
      }
   }
}
int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);

It's a very good idea to stay way from pointer arithmetic. Don't do this! You are essentially subtracting the pointer and divide that number by num_columns, and that number will be random.

If you want to get the row/column of an element, search the array one element at a time.

for(int row=0; row<num_rows; ++row) {
   for(int column=0; column<num_columns; ++column) {
      if (a[row][column] == element) {
         // we got it!
      }
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文