c++多维数组不能大于0

C++ multidimensional array cannot increase above 0

本文关键字:大于 不能 数组 c++      更新时间:2023-10-16

我编写了c++代码,创建了一个多维数组,其中每个条目都是0,除了9个包含9的值。我想写一个循环遍历数组的代码如果它找到一个数字大于0的元素,它就从这个数字中取1并把它加到相邻的单元格中。这似乎是有效的,但只有当相邻单元格中已经有一个大于0的数字时。

for(int x=0; x<max_row; x++){
for(int y=0; y<max_col; y++){
    if(map_array[x][y] > 0){
        int num = m_array[x][y];
        m_array[x][y]--; 
        m_array[x+1][y+1]++;
    }
}
}

这将生成一个数组,其中有一组8和9被0包围,而实际上外围应该是1。

我做错了什么?

我不明白你想做什么,什么是"相邻单元格",但在任何情况下,你的循环是无效的。有效循环至少看起来像

for ( int x = 0; x < max_row; x++ )
{
   for ( int y = 1; y < max_col; y++ )
   {
      if ( map_array[x][y-1] > 0 )
      {
        m_array[x][y-1]--; 
        m_array[x][y]++;
      }
   }
}

或者你想要下面的

int *p = reinterpret_cast<int *>( map_array );
for ( int i = 1; i < max_row * max_col; i++ )
{
    if ( p[i-1] > 0 )
    {
        --p[i-1];
        ++p[i];
    }
}
for ( const auto & a : map_array )
{
    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;
}