[英]Assigning types to a range of integers using enum?
我有一个索引数组[1 ... 20]。 indexesArray的前四个元素链接到某个类型的文件(称为类型A),其他16个元素链接到类型B。
我随机地调整数组。 我现在希望提取4个索引,但是最多只能提取4个索引之一。
我想我需要在这里使用枚举函数来将索引1-4定义为“ A型”,将索引5-20定义为“ B型”,那么如果我查看了例如我新随机化的indexsArray [0]的第一个元素,可以分辨出是哪种类型并采取相应措施。
我从示例中看到枚举的方式类似:
enum category { typeA = 0, typeB };
是否可以将索引1-4分配给typeA,将其余的索引分配给typeB,还是我在这里走错了路? 提前致谢。
编辑以包含代码段
我试图对此进行测试并立即遇到错误
#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;
}
你不在正轨。 您不能为1-4分配给定的枚举。 枚举常量只有一个值,只有一个。 你可以做的是使用一个枚举来定义两种类型,说typeA
和typeB
因为你已经做了,然后定义索引映射回类型的函数,例如
enum category categoryForIndex(int index) {
if (index >= 1 && index <= 4) {
return typeA;
} else {
return typeB;
}
}
现在,您可以对索引进行分类。
您无需先对数组进行混洗就可以做到这一点,这样您就知道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];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.