通过交集和并集组合 NSArray
我有两个共享一些公共元素的 NSArray A 和 B,例如,
A: 1,2,3,4,5
B: 4,5,6,7
我想创建一个新的 NSArray,其中包含两个 NSArray 之间的公共内容,并与第二个 NSArray 的内容相连接,同时保持元素的顺序并删除重复项。也就是说,我想要 (A ∩ B) ∪ B。
对先前 NSArray 的操作将产生:
A ∩ B: 4,5
(A ∩ B) ∪ B: 4,5,6,7
如何在 Objective-C 中完成此操作?
I have two NSArrays A and B that share some common elements, e.g.
A: 1,2,3,4,5
B: 4,5,6,7
I would like to create a new NSArray consisting of the contents common between the two NSArrays joined with the contents of the second NSArray while maintaining the order of the elements and removing duplicates. That is, I would like (A ∩ B) ∪ B.
The operation on the previous NSArrays would yield:
A ∩ B: 4,5
(A ∩ B) ∪ B: 4,5,6,7
How do I accomplish this in Objective-C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将
NSArray
转换为NSSet
,可以使用标准的集合操作。Convert the
NSArray
s toNSSet
s, the standard set operations are available.正如其他人所建议的,您可以使用
NSSet
轻松完成此操作。但是,这不会保留顺序。如果您想保留顺序并且可以面向 OS X 10.7+,那么您可以使用新的
NSOrderedSet
(和可变子类)做同样的事情。As others have suggested, you can easily do this with
NSSet
. However, this will not preserve ordering.If you want to preserve ordering and you can target OS X 10.7+, then you can use the new
NSOrderedSet
(and mutable subclass) to do the same thing.正如其他人指出的那样,通过使用 NSSet。因为
这可以解决欺骗问题,但不会维持秩序。您将获取“set”中的结果并将它们重新排序到数组中。没有原生的集合功能可以完成这一切——如果您希望保持顺序并单独担心重复,请使用 NSMutableArray 的
-removeObjectsInArray:
方法等。By using NSSet, as others have pointed out. For
This takes care of dupes but won't preserve order. You'd take the results in "set" and sort them back into an array. There's no native collection functionality that will do it all-- if you prefer to keep the order and worry about dupes separately, use NSMutableArray's
-removeObjectsInArray:
method, etc.(A ∩ B) ∪ B 总会给你 B,所以这是一个计算起来相当奇怪的事情。这就像说“给我所有绿色汽车的集合,以及所有汽车的集合”。这将为您提供所有汽车的集合。
(A ∩ B) ∪ B will always give you B, so this is a pretty bizarre thing to want to calculate. It's like saying "Give me the set of all cars that are colored green, combined with the set of all cars". That's going to give you the set of all cars.
您可以使用一个 NSSet 类来执行这些操作。
There is an
NSSet
class you can use to perform these operations.