通过交集和并集组合 NSArrays [英] Combining NSArrays Through Intersection and Union

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

问题描述

我有两个 NSArrays A 和 B,它们共享一些公共元素,例如

A: 1,2,3,4,5乙:4、5、6、7

我想创建一个新的 NSArray,其中包含两个 NSArray 之间的共同内容,并与第二个 NSArray 的内容相连,同时保持元素的顺序并删除重复项.也就是说,我想要 (A ∩ B) ∪ B.

对之前的 NSArray 的操作会产生:

A∩B:4,5(A ∩ B) ∪ B: 4,5,6,7

我如何在 Objective-C 中实现这一点?

解决方案

NSArrays转换为NSSets,标准集合操作可用.

NSArray *a = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];NSArray *b = [NSArray arrayWithObjects:@"4", @"5", @"6", @"7", nil];NSMutableSet *setA = [NSMutableSet setWithArray:a];NSSet *setB = [NSSet setWithArray:b];[setA intersectSet:setB];NSLog(@"c: %@", [setA allObjects]);

<块引用>

NSLog 输出:c:(4, 5)

[setA unionSet:setB];NSLog(@"d: %@", [setA allObjects]);

<块引用>

NSLog 输出:d: (6, 4, 7, 5)

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?

解决方案

Convert the NSArrays to NSSets, the standard set operations are available.

NSArray *a = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
NSArray *b = [NSArray arrayWithObjects:@"4", @"5", @"6", @"7", nil];

NSMutableSet *setA = [NSMutableSet setWithArray:a];
NSSet *setB = [NSSet setWithArray:b];
[setA intersectSet:setB];
NSLog(@"c: %@", [setA allObjects]);

NSLog output: c: (4, 5)

[setA unionSet:setB];
NSLog(@"d: %@", [setA allObjects]);

NSLog output: d: (6, 4, 7, 5)

这篇关于通过交集和并集组合 NSArrays的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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