[英]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.