在Objective-C中存储和检索数字对的快速方法
发布时间:2020-12-16 07:28:49 所属栏目:百科 来源:网络整理
导读:我正在实现排队的泛洪填充算法,需要在NSMutableArray中存储和检索数字对. 基本上,我正在创建一个数组 m_queue = [NSMutableArray array]; 然后在某个时候我填充数组 [m_queue addObject:[NSValue valueWithCGPoint:CGPointMake(x + 1,y)]]; 然后我检索下一次
我正在实现排队的泛洪填充算法,需要在NSMutableArray中存储和检索数字对.
基本上,我正在创建一个数组 m_queue = [NSMutableArray array]; 然后在某个时候我填充数组 [m_queue addObject:[NSValue valueWithCGPoint:CGPointMake(x + 1,y)]]; 然后我检索下一次迭代的数据并删除数组开头的值 NSValue* value = [m_queue objectAtIndex:0]; [m_queue removeObjectAtIndex:0]; CGPoint nextPoint = [value CGPointValue]; [self queueFloodFill8:nextPoint.x y:nextPoint.y]; 问题是:我该怎么做才能避免创建大量的CGPoint和NSValue对象? 我真的不需要点,算法使用整数值对,所以我认为可能有更好的方法来存储这些对. 更新: 我已经介绍过了 typedef struct lookup_point_struct { int x; int y; struct lookup_point_struct* next; } LookupPoint; 并重写代码以使用此类结构的链表而不是NSMutableArray和CGPoint / NSValue. 所有这些使我的代码快了大约3倍.而且内存消耗也显着下降. 解决方法
除了可能创建自己的类(如NumberPair)或者放入数组而不是使用NSValue和CGPoint之外,实际上没有更好的Objective-C / Foundation方法.这样做可能稍微有点内存效率,你可以让NumberPair包含两个整数,而不是像你一样关注的浮点数.就像是:
@interface NumberPair : NSObject @property (nonatomic,assign) int x; @property (nonatomic,assign) int y; @end @implementation NumberPair @synthesize x,y; @end ... m_queue = [NSMutableArray array]; NumberPair *newPair = [[NumberPair alloc] init]; newPair.x = 1; newPair.y = 2; [m_queue addObject:newPair]; ... NumberPair *nextPoint = [m_queue objectAtIndex:0]; [m_queue removeObjectAtIndex:0]; [self queueFloodFill8:nextPoint.x y:nextPoint.y]; 除此之外,你可以做一个更像C的东西,让结构包含两个整数,创建一个动态分配的数组来存储结构(你需要知道队列的最大大小或保持重新分配).就像是: typedef struct { int x; int y; } NumberPair; NumberPair *m_queue = (NumberPair*)malloc(sizeof(NumberPair) * QUEUE_SIZE); // ... etc 此外,您可能想要查看我的包含NSMutableArray的MJGStack类,以提供类似于接口的堆栈,您可以稍微调整以执行您想要的操作,而不是直接使用NSMutableArray.虽然这绝不是必要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |