简体   繁体   English

如何在Objective-C中添加和更新二维数组的对象?

[英]How to add and update the objects of two dimensional array in objective-c?

I want to make a two dimensional array in objective-c and initialize all the indexes as zero. 我想在Objective-C中创建一个二维数组,并将所有索引初始化为零。 whenever my data (2D Coordinate) matches with any row/column then I want to upgrade the respective index by value one. 每当我的数据(2D坐标)与任何行/列匹配时,我都希望通过值1升级相应的索引。 So that later on I can scan for my highly probable coordinate on the basis of maximum number of index at any point. 这样一来,以后我就可以在任意点基于最大索引数扫描我的高度可能坐标。 For eg: If my algorithm generates coordinate (0,1), then the index at first row and second column must increase by one. 例如:如果我的算法生成坐标(0,1),则第一行和第二列的索引必须增加一个。 Thanks a lot. 非常感谢。

Here is how you create your array. 这是创建数组的方式。

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:[NSMutableArray arrayWithObjects:@"0",@"0",nil]];
[array addObject:[NSMutableArray arrayWithObjects:@"0",@"0",nil]];
NSLog(@"%@",array);

Update value 更新值

Say you want to update index(0,1) with value 3 , you do 假设您要用值3更新index(0,1) ,您可以

[[array objectAtIndex:0] replaceObjectAtIndex:1 withObject:@"3"];
NSLog(@"%@",array);

Update index(1,1) with value 4 do 用值4更新index(1,1)

[[array objectAtIndex:1] replaceObjectAtIndex:1 withObject:@"4"];
NSLog(@"%@",array);

Hope it helps. 希望能帮助到你。

Cheers. 干杯。

如果需要,可以使用数字并使用简单的方法来编写数组:

NSMutableArray * array2d = @[@[@0,@0], @[@0,@1]];

Just a suggestion: 只是一个建议:

Objective-C is a super set of C. So you can make use of the C array concept also. Objective-C是C的超集。因此,您也可以使用C数组的概念。

int array2D[5][5] = {0};//The compiler will automatically intialize all indces to 0.

or use 或使用

memset(&a[0][0], 0, sizeof(int) * 5 * 5);

then use the simple C assignment like as follows, 然后使用如下所示的简单C赋值,

array2D[0][1] = 3;

which is much faster and simple. 更快,更简单。

Sample Code: 样例代码:

#include<stdio.h>
#include<string.h>

int main(int argc, char * argv[])
{
  int a[5][5];

  memset(&a[0][0], 0, sizeof(int) * 5 * 5);

  for(int  i = 0;  i < 5; i++)
  {
    for(int j = 0; j < 5; j++)
    {
      printf("%d ", a[i][j]);
    }

    printf("\n");
  }

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM