使用枚举将类型分配给一系列整数?

时间:2012-01-31 20:16:32

标签: objective-c c enums

我有一系列索引[1 ... 20]。 indicesArray的前4个元素链接到某种类型的文件(称为类型A),其他16个元素链接到类型B.

我随机乱拨阵列。我现在希望提取4个索引,但最多只有4个中的一个可以是A类型。

我想我需要在这里使用枚举函数将索引1-4定义为“类型A”&索引5-20为“B型”,那么如果我查看例如我新近随机的indicesArray [0]的第一个元素我可以分辨它是哪种类型&相应地采取行动。

我从例子中看到的enum使用的方式如下:

enum category { typeA = 0, typeB };

是否可以将索引1-4分配给typeA&其余的是打字B,还是我在错误的轨道上?提前谢谢。

修改以包含代码段

我试图测试这个&马上遇到了错误

 #import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int* indices = malloc(20*sizeof(int));

for (int i=0; i<20; i++) {

    indices[i] = i;

}

enum category {typeA, typeB};


enum category categoryForIndex(int index) {
    if (index >= 1 && index <= 4) {
        return typeA;
    } else {
        return typeB;
    }
}

[pool drain];
return 0;

}

当我尝试编译它时,我得到错误“嵌套函数被禁用,使用-fnested-functions重新启用”,这通常发生在第二个main被意外抛入混合中,或者某些东西时。有任何想法吗?

编辑以包含一些显示如何将解决方案付诸实践的代码

#import <Foundation/Foundation.h>

enum category {typeA, typeB};

enum category categoryForIndex(int index) {
if (index >= 1 && index <= 4) {
    return typeA;
   } else {
    return typeB;
    }

}

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int* indices = malloc(20*sizeof(int));

for (int i=1; i<=20; i++) {

    indices[i] = i;

}


NSLog(@"index[0] is %i:", indices[16]);

enum category index;

index = indices[16];

switch (categoryForIndex(index)) {   //this tests to see what category 16 belongs to
    case typeA:
        NSLog(@"index is of type A");   
        break;
    case typeB:
        NSLog(@"index is of type B");
        break;
    default:
        NSLog(@"index not valid");
        break;
}

 [pool drain];
 return 0;

}

2 个答案:

答案 0 :(得分:1)

你偏离轨道。您不能指定1-4给定的枚举。枚举常量只有一个值,只有一个。您可以做的是使用枚举来定义两种类型,比如您已经完成的typeAtypeB,然后定义一个将索引映射回类型的函数,例如

enum category categoryForIndex(int index) {
    if (index >= 1 && index <= 4) {
        return typeA;
    } else {
        return typeB;
    }
}

现在您可以对索引进行分类。

答案 1 :(得分:0)

你可以在没有先洗牌的情况下做到这一点,这样你就知道A总是在前面:

#define IndexCount 20
#define ExtractCount 4
#define TypeACount 4

int indicesRemainingCount = IndexCount;
int indices[IndexCount] = { ... }; // your indices, first 4 are type A
int chosenIndices[ExtractCount]; // to be filled with random elements from indices, max one of type A

int minIndex = 0;
for (int i = 0; i < ExtractCount; ++i) {
    int j = minIndex + arc4random_uniform(indicesRemainingCount - minIndex);
    chosenIndices[i] = indices[j];
    if (j < TypeACount) {
        // Set minIndex so I won't pick another A.
        minIndex = TypeACount;
    } else {
        // Remove the chosen B so I don't pick it again.
        --indicesRemainingCount;
        indices[j] = indices[indicesRemainingCount];
    }
}