【问题标题】:Sorted Array or Map in Objective C?Objective C中的排序数组或映射?
【发布时间】:2012-04-17 04:10:53
【问题描述】:

我正在 iOS 上的 Objective-C 中搜索排序的数组或映射(Dict...whatever)。

是否有类似的东西(插入时排序)还是我必须覆盖 getter/setter 并“自行”对数据结构进行排序?我知道,可以对数组进行排序,但我想知道是否有像 Java 中的 TreeMap 这样的“自动”方式,您可以在其中放置一个条目,并将其直接插入正确的位置。

干杯,

马克

【问题讨论】:

  • 不是骗子,但接受的答案很有用:stackoverflow.com/questions/1648059/…
  • 谢谢,这有帮助...但我希望避免在我的项目中使用另一个库。
  • 您可以实现自己的容器,或者按照您希望它们排序的任何顺序保留一个哈希键数组。
  • @mkb:这个问题询问的是 ordered 容器(即按插入顺序),它与 sorted 容器 完全不同

标签: objective-c ios arrays map


【解决方案1】:

如果你想要一个数组,最简单的方法可能是在 NSMutableArray 上创建一个类别,方法是在正确的位置插入一个对象。但是,这有点令人不满意(没有什么可以阻止您使用普通方法插入对象并破坏排序),因此您可能想要自己的集合类。您可以通过将 NSMutableArray 和 comparator 包装在一个新类中来轻松创建它。例如

@interface MyOrderedArray : NSObject <NSFastEnumeration>

-(id) initWithComparator: (NSComparator) anOrdering;

-(void) insertObject: (id) aNewObject;

// methods to access objects from the array

@end

@implementation MyOrderedArray
{
   NSComaparator theOrdering;
   NSMutableArray* backingArray;
}

-(id) initWithComparator: (NSComparator) anOrdering
{
    self = [super init];
    if (self != nil)
    {
        theOrdering = [anOrdering copy];
        backingArray = [[NSMUtableArray alloc] init];
}

-(id) insertObject: (id) newObject
{
    // use a binary search to find the index and insert the object there
}

其他方法可以传递给后备数组来实现,例如

-(NSUInteger) count
{
    return [backingArray count];
}

这个会很有用:

- (NSUInteger)countByEnumeratingWithState: (NSFastEnumerationState*) state 
                                  objects: (id*) stackbuf 
                                    count: (NSUInteger) len
{
    return [backingArray countByEnumeratingWithState: state 
                                             objects: stackbuf 
                                               count: len];
}

【讨论】:

  • 这种方法效率低下:插入一个元素需要 O(n);而在自平衡二叉搜索树实现中,插入需要 O(log n)
  • @user102008:您是否注意到我没有为-insertObject: 提供实现,并且占位符注释说“使用二进制搜索”?二进制搜索是 O(log n) 并且你不必编写一个全新的容器类
  • 但是插入它需要 O(n)
  • @user102008:您是否对 NSMutableArray 的实现做出了毫无根据的假设?
  • 你能想到任何不正确的实现吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 2012-04-25
相关资源
最近更新 更多