我有cpp代码,其中结构对象被放入CLISTS中。我正在将这段代码移植到Objective C中。
CLIST类似于具有.RemoveAt、.GetAt、.InsertBefore、.GetNext、.GetHeadPosition函数的双向链表。
如何在Objective C中实现同样的功能。我是否需要在Objective C.Is中实现双向链表?是否有其他预定义的方法可以使用它?
发布于 2011-05-16 22:41:23
CLIST大概是圆形的?因此就有了GetHeadPosition
在任何情况下,NSArray (或者在本例中是NSMutableArray,因为您希望插入)是在Objective-C中保持有序列表的正常方法。
对于RemoveAt,请使用removeObjectAtIndex:。对于GetAt,请使用objectAtIndex:。对于InsertBefore,你可能想要写一些类似这样的代码:
- (void)insert:(id)objectToInsert before:(id)referenceObject
{
int index = [array indexOfObject:referenceObject];
if(index == NSNotFound) return; // or whatever you'd expect.
// Maybe object is just inserted at the end?
index = index - 1;
if(index < 0) index = [array count];
[array insertObject:objectToInsert atIndex:index];
}(这在NSArray类别中可能会更好,但您明白这一点)
对于GetNext和GetHeadPosition,您可能希望将数组位置保存在单独的变量中。因此,对于GetNext:
arrayPosition = (arrayPosition + 1)%[array count];
return [array objectAtIndex:arrayPosition];而对于GetHeadPosition,只需:
return arrayPosition;编辑:对于遍历NSArray,最简单的方法实际上是忽略任何显式的内容,只需使用:
for(ObjectType *object in array)
{
/* do something with object */
}这通常意味着你实际上不需要GetNext的模拟,但是你不能在那个循环中改变数组,所以它并不总是可用的。
https://stackoverflow.com/questions/6017537
复制相似问题