c++多维数组不能大于0
C++ multidimensional array cannot increase above 0
我编写了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;
}
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的for循环不能正确获取argv
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么模板类中的对象不能返回值
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 数组长度,为什么从命令行获取时不能使用它?
- CStdioFile 不能处理大于 2GB 的文件?
- 16 位系统中的程序如何访问大于 65535 的整数,但不能访问地址
- 第 k 个最小元素 - 不能创建大于 k 大小的数组
- 为什么 UInt64 变量不能包含大于 UInt32::Max 的值?
- 为什么 CSpinButtonCtrl 不能正确处理大于 1000 的数字?
- 为什么我的代码不能为大于N=508的值工作
- c++多维数组不能大于0
- libcurl + openssl不能下载大于2GB的文件
- 为什么我的8M L3缓存不能为大于1M的数组提供任何好处?