gpt4 book ai didi

objective-c - 将两个 NSArray 并排排序

转载 作者:太空狗 更新时间:2023-10-30 03:27:23 25 4
gpt4 key购买 nike

我有几个数组需要并排排序。

例如,第一个数组的名称为:@[@"Joe"、@"Anna"、@"Michael"、@"Kim"],以及另一个数组包含地址:@[@"Hollywood bld", @"Some street 3", @"That other street", @"country road"],数组的索引放在一起. “Joe”住在“Hollywood bld”等等。

我想按字母顺序对 names 数组进行排序,然后将 address 数组排序在一起,这样它们仍然在一起,“Hollywood bld”与“Joe”具有相同的索引。我知道如何用

对一个数组按字母顺序排序
NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];

但是有什么简单的方法可以使用适当的顺序对第二个数组进行排序吗?

最佳答案

  1. 创建一个置换数组,初始设置为p[i]=i
  2. 根据第一个数组的name键对排列排序
  3. 使用排列对两个数组重新排序

示例:假设第一个数组是 {"quick", "brown", "fox"}。排列以 {0, 1, 2} 开始,排序后变为 {1, 2, 0}。现在您可以遍历排列数组,并根据需要对原始数组和第二个数组重新排序。

NSArray *first = [NSArray arrayWithObjects: @"quick", @"brown", @"fox", @"jumps", nil];
NSArray *second = [NSArray arrayWithObjects: @"jack", @"loves", @"my", @"sphinx", nil];
NSMutableArray *p = [NSMutableArray arrayWithCapacity:first.count];
for (NSUInteger i = 0 ; i != first.count ; i++) {
[p addObject:[NSNumber numberWithInteger:i]];
}
[p sortWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
// Modify this to use [first objectAtIndex:[obj1 intValue]].name property
NSString *lhs = [first objectAtIndex:[obj1 intValue]];
// Same goes for the next line: use the name
NSString *rhs = [first objectAtIndex:[obj2 intValue]];
return [lhs compare:rhs];
}];
NSMutableArray *sortedFirst = [NSMutableArray arrayWithCapacity:first.count];
NSMutableArray *sortedSecond = [NSMutableArray arrayWithCapacity:first.count];
[p enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSUInteger pos = [obj intValue];
[sortedFirst addObject:[first objectAtIndex:pos]];
[sortedSecond addObject:[second objectAtIndex:pos]];
}];
NSLog(@"%@", sortedFirst);
NSLog(@"%@", sortedSecond);

关于objective-c - 将两个 NSArray 并排排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12436927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com