c++ - 设置类似命名变量的值 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", " "
};
数据集和逻辑都有效,我只是找不到设置变量值的简单方法。
解决方案
我的问题的解决方案是将我的一长串整数列表转换为一个向量/数组。
所以而不是:
int rect1Color;
int rect2Color;
int rect3Color;
...
int rect63Color;
int rect64Color;
我现在有:
int rectColor1[64];
用户“cigien”:
只需使用vector<int> rectColors;
. 然后索引i
对应于第i
th 种颜色。
用户“user4581301”:
旁注:如果您在编译时有固定数量的已知变量,请考虑使用std::array
。因为大小是固定的,所以开销小于动态大小所需的开销std::vector
推荐阅读
- python - Python + Flask + Discord:如何通过flask端点通过discord发送消息?
- magento - Magento 2 结帐时脚本(地图 - INPOST)的问题 - 运输方式
- python - 带有 APScheduler 的 Pyinstaller - 带有 IntervalTrigger 的 TypeError
- xslt - 如何调整我的 XSLT 脚本以将 Q# 替换为 Q1、Q2、Q3 等?
- python - 网络抓取地图Python,Splinter的麻烦
- r - 从旧向量创建新向量时,有没有办法从旧向量的索引中获取信息
- screeps - 添加然后访问控制器上的内存
- javascript - 如何从 OBJ 模型中正确渲染 Three.js 中的四线框?
- ruby - 如何在 Webrick 代理服务器上修改 HTML 内容?
- python - 模拟游戏窗口中的点击