查找NSMutableArrays的交集 [英] Finding Intersection of NSMutableArrays

查看:78
本文介绍了查找NSMutableArrays的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个NSMutableArray,其中包含根据不同的标准添加到列表中的名称。

I have three NSMutableArray containing names that are added to the lists according to different criterieas.

这是我的数组伪代码:

NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"];
NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"];
NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"];

我想找到第四个数组,其中包括这三个数组的交集。在这种情况下,例如它将是:

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

NSMutableArray *array4 = [@"Jack",@"Lisa"];

因为所有三个阵列都有jack和lisa作为元素。有没有办法简单地这样做?

Because all the three array have jack and lisa as an element. Is there way of simply doing this?

推荐答案

使用 NSMutableSet

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

唯一的问题是你丢失了元素的排序,但我认为(在这种情况下)那没关系。

The only issue with this is that you lose ordering of elements, but I think (in this case) that that's OK.

正如评论中指出的那样(谢谢, Q80 !),iOS 5和OS X 10.7添加了一个名为 NSOrderedSet 的新类(带有 Mutable 子类),允许您在保持顺序的同时执行这些相同的交叉操作。

As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 added a new class called NSOrderedSet (with a Mutable subclass) that allows you to perform these same intersection operations while still maintaining order.

这篇关于查找NSMutableArrays的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆