我想按数组的对象对数组进行排序,然后获取索引,如下所示:
NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects: @"3", @"2", @"1", @"0", @"1", @"2", nil];
我希望对象的索引按升序排列。在这里,因为最低值的索引为 3,所以索引将为:3、2、4、1、5、0 或类似的值。
有什么想法吗?
谢谢!
最佳答案
这就是我最终所做的:
//Create a mutable array of the indexes in the myArray (just a list from 0...n)
NSMutableArray *indexes = [[NSMutableArray alloc] init];
for (int i = 0; i < myArray.count; i++){
[indexes addObject: [NSNumber numberWithInteger:i]];
}
//Create a dictionary with myArray as the objects and the indexes as the keys
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjects:myArray forKeys:indexes];
//Create an array of myArray's keys, in the order they would be in if they were sorted by the values
NSArray *sorted = [tempDictionary keysSortedByValueUsingSelector: @selector(compare:)];
关于iphone - 如何从另一个已排序的数组中获取索引数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3614192/