C ++:在switch语句中构建阵列 [英] C++: Construct arrays inside a switch statement
问题描述
我试图构建具有其中一个将被随机选择了几个不同配置的阵列。在code我第一次尝试是:
I'm trying to construct an array that has a few different configurations where one will be selected randomly. The code I tried first is:
void createArray() {
int* tileVals;
int randInt = rand() % 3;
switch (randInt) {
case 0:
int tileVals[] = {1,1,1,2,2,2,3,3,3};
break;
case 1:
int tileVals[] = {1,1,1,1,2,2,3,3,3};
break;
case 2:
int tileVals[] = {1,1,1,1,2,2,2,3,3};
break;
}
// Do stuff with tileVals
}
但我得到的编译器错误:
But I got the compiler error:
src/Board.cpp:67:7: error: redefinition of 'tileVals'
int tileVals[] = {1,1,1,1,2,2,2,3,3};
src/Board.cpp:70:7: error: redefinition of 'tileVals'
int tileVals[] = {1,1,1,2,2,2,2,3,3};
...
我明年受审:
void createArray() {
int* tileVals;
int randInt = rand() % 3;
switch (randInt) {
case 0:
int case0[] = {1,1,1,2,2,2,3,3,3};
tileVals = case0;
break;
case 1:
int case1[] = {1,1,1,1,2,2,3,3,3};
tileVals = case1;
break;
case 2:
int case2[] = {1,1,1,1,2,2,2,3,3};
tileVals = case2;
break;
}
// Do stuff with tileVals
}
但是,这回来了一个编译器错误:
But this came back with a compiler error:
src/Board.cpp:85:2: error: switch case is in protected scope
case 6:
^
src/Board.cpp:82:7: note: jump bypasses variable initialization
int case5[] = {1,1,1,2,2,3,3,3,3};
...
我知道我可以通过具有每个案例语句然后分配值是switch语句之外创建的tileVals数组中环做,但是这似乎并不像一个非常有效的方式来做到这一点。有没有更好的办法?谢谢你。
I know I could do it by having a for loop inside each case statement that then assigned the values to a tileVals array that is created outside the switch statement, but that doesn't seem like a very efficient way to do this. Is there a better way? Thanks.
推荐答案
如果您不要修改 tileVals
在以后code的内容,你可以做它如下:
If you do not modify the content of tileVals
in the later code, you could do it as follows:
void createArray() {
int * tileVals;
int randInt = rand() % 3;
int cases[][9] = { {1, 1, 1, 2, 2, 2, 3, 3, 3},
{1, 1, 1, 1, 2, 2, 3, 3, 3},
{1, 1, 1, 1, 2, 2, 2, 3, 3} };
tileVals = cases[randInt];
// Do stuff with tileVals
}
这篇关于C ++:在switch语句中构建阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!