【问题标题】:Compare two items in one NSArray比较一个 NSArray 中的两个项目
【发布时间】:2013-05-15 19:34:34
【问题描述】:

我有一个包含二十个项目的数组。我想在数组中搜索,将一项与数组中的下一项进行比较,然后打印较大的项。我已经对数组进行了排序。我只想比较这两个项目,检查两个值之间的余数,如果大于等于四,则打印较大的项目。

【问题讨论】:

  • 在每对值之间,或者两个特定索引处的值之间,还是什么?你的价值观是NSNumbers 吗?
  • 迭代。有几种不同的方法可以做到这一点,但一个普通的旧 for 循环应该就可以了。
  • 一些比较好的做法here
  • 它是一个对象数组,其名称为 NSString,points 为 int。我想比较整数。

标签: objective-c arrays cocoa comparison nsarray


【解决方案1】:
NSArray* arr = [NSArray arrayWithObjects:
    [NSNumber numberWithInt:1],
    [NSNumber numberWithInt:6],
    [NSNumber numberWithInt:7],
    [NSNumber numberWithInt:11],
    nil
];

int len = [arr count];

for (int i=0; i < len-1; ++i) {

    int num1 = [[arr objectAtIndex:i] intValue];
    int num2 = [[arr objectAtIndex:i+1] intValue];

    if ( num2-num1 > 4 ) {
        NSLog(@"%d", num2);
    }
}

 --output:--
    6

【讨论】:

  • num2 在下一次迭代中将是 num1。只需在进入 for 循环之前设置一次 num1,它应该从 1 -
【解决方案2】:
NSEnumerator *itemEnumerator = [theArray objectEnumerator];
YourClass *lastObject = [itemEnumerator nextObject];
YourClass *compareObject;
while( (compareObject = [itemEnumerator nextObject]) != nil)
{
  if( /* place your condition here */ )
  {
     NSLog( … );
  }
  lastObject = compareObject;
}

在 Safari 中输入

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多