首页 > 解决方案 > 设置类似命名变量的值 C++

问题描述

所以,我有一些变量声明如下:

int rect1Color;
int rect2Color;
int rect3Color;
...
int rect63Color;
int rect64Color;

我需要根据如下所示的循环更改每个变量:

for (int i = 0; i < sizeof(playPos) / sizeof(char*); ++i) {
    const char* TEMP = playPos[i];
    if (TEMP != " x" && TEMP != " o" && TEMP != "xx" && TEMP != "oo") {
        if (TEMP == " p") {
            rect[i+1]Color = 1;
        }
        else {
            rect[i+1]Color = 2;
        }
    }
    else if (TEMP == " o" || TEMP == "oo") {
        rect[i+1]Color = 3;
    }
    else if (TEMP == " x" || TEMP == "xx") {
        rect[i+1]Color = 4;
    }
}

从这个数据集中得出:

const char *playPos[64] {
    "  ", " o", "  ", " o", "  ", " o", "  ", " o",
    " o", "  ", " o", "  ", " o", "  ", " o", "  ",
    "  ", " o", "  ", " o", "  ", " o", "  ", " o",
    "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ",
    "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ",
    " x", "  ", " x", "  ", " x", "  ", " x", "  ",
    "  ", " x", "  ", " x", "  ", " x", "  ", " x",
    " x", "  ", " x", "  ", " x", "  ", " x", "  "
};

数据集和逻辑都有效,我只是找不到设置变量值的简单方法。

标签: c++loops

解决方案


我的问题的解决方案是将我的一长串整数列表转换为一个向量/数组。

所以而不是:

int rect1Color;
int rect2Color;
int rect3Color;
...
int rect63Color;
int rect64Color;

我现在有:

int rectColor1[64];

用户“cigien”: 只需使用vector<int> rectColors;. 然后索引i对应于第ith 种颜色。

用户“user4581301”: 旁注:如果您在编译时有固定数量的已知变量,请考虑使用std::array。因为大小是固定的,所以开销小于动态大小所需的开销std::vector


推荐阅读