【发布时间】:2012-01-31 20:16:32
【问题描述】:
我有一个索引数组 [1 ... 20]。 indicesArray 的前 4 个元素链接到某个类型的文件(称为 A 类),其他 16 个元素链接到 B 类。
我随机打乱数组。我现在希望提取 4 个索引,但最多 4 个索引中只有一个可以是 A 类型。
我想我需要在这里使用枚举函数将索引 1-4 定义为“类型 A”,将索引 5-20 定义为“类型 B”,然后如果我查看例如我新随机化的 indicesArray[0] 的第一个元素我可以判断它是哪种类型并采取相应的行动。
我从示例中看到枚举使用的方式类似于:
enum category { typeA = 0, typeB };
是否可以将索引 1-4 分配给 typeA 并将其余的分配给 typeB,还是我在这里走错了路?提前致谢。
编辑以包含代码 sn-p
我尝试对此进行测试并立即遇到错误
#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 重新启用”,这通常发生在第二个主函数意外加入混音或类似情况时。有任何想法吗?
编辑以包含一些显示如何将解决方案付诸实践的代码
#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;
}
【问题讨论】:
-
注意 C 中的索引从
0到N-1,包括在内。 -
感谢 pmg :) 是的,我指的数组包含索引(恰好从 1 开始)
标签: objective-c c enums