如何定位 NSMutableArray 中的最大值和位置
我需要在可变数组中搜索最大值并返回其位置和值。我只想遍历数组一次,我不确定这是否可能,
我想要完成的示例可以在
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
NSObject *max = [array valueForKeyPath:@"@max.self"];
max
对象下面演示,它似乎只包含该值(而不是位置)。这可以通过调试器使用 print-object max
进行演示
有什么建议吗?
I need to search a mutable array for the maximum value and return its position as well as value. I'd only like to iterate through the array once and I'm not sure if that's possible
an example of what I'm trying to accomplish can be demonstrated below
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
NSObject *max = [array valueForKeyPath:@"@max.self"];
the max
object only seems to contain the value (and not the position). this can be demonstrated through the debugger with print-object max
Any advice out there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
valueForKeyPath:@"@max.self"
很棒,但前提是您想要最大值。要在一次迭代中同时了解索引和值,我会使用
enumerateWithBlock:
相当多的代码,但您只在数组中迭代一次。
Using
valueForKeyPath:@"@max.self"
is great, but only if you want the maximum value.To know both index and value in one iteration, I'd use
enumerateWithBlock:
Quite more code, but you're iterating only once in the array.
如果您不担心数组中可能存在多个相同的最大值,则可以使用
-indexOfObject:
来获取索引。它将返回数组中第一次出现的对象。If you're not worried about the possibility of there being more than one identical maximum value in the array, you can use
-indexOfObject:
to get the index. It will return the first occurrence of the object in the array.我希望以下解决方案将帮助您识别数组中的最大值。
如有任何问题,请告诉我。
I hope, following solution will help you to identify maximum value from array.
Please let me know if any issue.
在这里你可以找到处理集合和KVC的正确方法
这是马特的好帖子
http://nshipster.com/kvc-collection-operators/
Here you can find correct way to deal with collections and KVC
Its nice Post by Matt
http://nshipster.com/kvc-collection-operators/