c++ - 编写一个循环以更改具有不同名称的 int 数组中的值

标签 c++ arrays loops input

我的标题有点令人困惑,但我正在尝试编写一个循环来更改 81 个具有不同名称的数组中的值。我想用一个值或一个值数组启动数组。这是我的数独求解器代码的一部分,因为我认为我没有很好地解释它。

int cell1[], cell2[9], cell3[9],cell4[9]......cell81[9]; // <-- this will make 81 cells with an array that can hold a possible of 9 candidates

cout << "User input: << endl; // lets use ...1.5...14....67..8...24...63.7..1.9.......3.1..9.52...72...8..26....35...4.9...
                              // as an example

假设我将该输入存储到一个字符数组中,并且我将使用循环来决定是启动给定值还是“.”。作为空值。

对于空值,我希望用 1-9 个值来初始化数组。我可以使用这段代码轻松地做到这一点。

If( ( (int)charArray[ 0 ] - 48) > 0 ) {   // type cast to int. Neg = initialize array with 1-9
                                         // pos = initialize with original value

cell1[ 0 ] =  (int)charArray[ 0 ] - 48;
} else {

cell1[ 9 ] = { 1,2,3,4,5,6,7,8,9};
}

我想避免为 81 个单元格编写此代码 81 次(被视为编写垃圾代码)。我不知道如何编写循环。我乐于接受关于如何使用类、函数等编写不同代码的建议。在此先感谢。

最佳答案

cell 数组创建为二维数组,具有 81 行和 9 列。

int cell[81][9];

现在您可以使用语法 cell[r][c] 遍历它们。例如,

for( i = 0; i < 81; ++i ) {
  cell[i][0] = 1;
  // ...
  cell[i][8] = 9;
}

如果您不想使用二维数组,您可以将该数组声明为一维数组,并适本地对其进行索引。

int cell[81 * 9];

for( i = 0; i < 81; ++i ) {
  cell[i + 0*81] = 1;
  // ...
  cell[i + 8*81] = 9;
}

关于c++ - 编写一个循环以更改具有不同名称的 int 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13061858/

相关文章:

c++ - 函数模板和派生类

c++ - 我收到 'Invalid Type Int[Int]...' ,但它没有任何意义

php - 正则表达式数组与字符串问题

ruby-on-rails - 一次渲染 n 个对象,插入代码然后重复接下来的 n 个对象 - Rails

html - 如何在 SVG 标签上循环 CSS 动画

Javascript - 创建一个增量为 30 步的 for 循环

二级层次类 : do not understand why it does not work 中的 C++ 多态性

c++ - 将 Uint8 转换为 unsigned char RGB 值

c++ - 基本模板 C++

python - Numpy 数组 : Efficient use of arrays containing indices