找对象的索引数组来查找相应的对象,在其他数组 [英] Get index of object in array to look up corresponding object in other array

查看:339
本文介绍了找对象的索引数组来查找相应的对象,在其他数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组。一个是名称的数组,而另一个是标题为是或否的字符串组成的阵列。每个名称的名称阵列中的索引路径对应的是/否阵列中的相同的索引的路径。例如:

I have two arrays. One is an array of names and the other is an array made up of strings titled "Yes" or "No". The index path of each name in the "name" array corresponds with the same index path in the "Yes/No" array. For example:

Names Array | Yes/No Array
Person 1    | Yes
Person 2    | No
Person 3    | Yes

什么是查找一个人的名字(可能得到它的索引路径),并检查它们是否是或否的是/否阵列中的最简单的方法是什么?

What would be the easiest way to look up a person's name (possibly getting the index path of it) and check whether they are "Yes" or "No" in the "Yes/No" array?

另外,我不知道,如果索引路径就是用正确的术语。如果不是,我的意思是一个目的是在阵列的数目。

Also, I'm not sure if "index path" is the right term to use. If it isn't, I mean the number that an object is in an array.

推荐答案

的NSArray 有一个名为方法 indexOfObject 的将返回要么指数最低,其相应的数组值,如果没有这样一个对象被发现等于或anObject NSNotFound。如果你的名字的数组不排序,然后用它来获取索引,然后可以插入到是/否数组。也就是说,这些方针的东西:

NSArray has a method called indexOfObject that will return either the lowest index whose corresponding array value is equal to anObject or NSNotFound if no such object is found. If your array of names is unsorted, then use this to get the index that you can then plug in to the Yes/No array. That is, something along these lines:

NSString *answer = nil;
NSUInteger index = [namesArray indexOfObject:@"John Smith"];
if (index != NSNotFound) {
    answer = [yesNoArray objectAtIndex:index];
}
return answer;

由于Bavarious问我在哪里的问题承担,这里的时候名称数组按字母顺序排序更好的方法。

Because Bavarious asks questions where I assume, here's a better way when the array of names is sorted alphabetically.

int index = [self findName:@"John Smith"];
NSString *answer = nil;
if (index >= 0) {
    answer = [yesNoArray objectAtIndex:index];
}
return answer;

其中函数 findName 是一个简单的二进制搜索:

where the function findName is a simple binary search:

-(int)findName:(NSString *)name {
    int min, mid, max;
    NSComparisonResult comparisonResult;
    min = 0;
    max = [namesArray count]-1;
    while (min <= max) {
        mid = min + (max-min)/2;
        comparisonResult = [name compare:[namesArray objectAtIndex:mid]];
        if (comparisonResult == NSOrderedSame) {
            return mid;
        } else if (comparisonResult == NSOrderedDescending) {
            min = mid+1;
        } else {
            max = mid-1;
        }
    }   
    return -1;  
}

这篇关于找对象的索引数组来查找相应的对象,在其他数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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