我有一個大小[4344][20]為2D_array 的 2D_array ,出于某些原因,我想在前 20 行之間傳輸,然后移動到接下來的 20 行,然后移動到接下來的 20 行......等等,直到到達最后一行,即第 4343 行.
我這樣做正確嗎?
我的代碼:
int main()
{
int tindex = 0;
for (int l = tindex; l 20 < 4344; l 20) {
for (int u = tindex; u < tindex 20; u) {
............
}
tindex = tindex 20;
}
}
uj5u.com熱心網友回復:
這就是我將如何使用 C (從 C 11 開始)。雖然我什至可能不會直接使用該陣列,而是將它包裝在一個類中并傳遞該類。(我會在它代表什么之后命名這個類,陣列只是 HOW)。我還會對類的陣列成員函式進行任何操作。
所以我的問題是陣列代表什么?
#include <utility>
// only use "magic" numbers once in your code
constexpr std::size_t rows_v = 4344;
constexpr std::size_t cols_v = 20;
// this is the syntax for passing your array to a function
void loop_over_array(const int(&arr)[rows_v][cols_v])
{
// this example uses range based for loops
// which cannot go out of bound of the array
// loop over all the rows in your array
// https://en.cppreference.com/w/cpp/language/range-for
for (auto& row : arr)
{
// loop over all the values in your row
for (auto& value : row)
{
// do something with value;
}
}
}
int main()
{
int my_array[rows_v][cols_v]{}; // initialize array to all 0
loop_over_array(my_array);
}
uj5u.com熱心網友回復:
/// Your code ///
int tindex = 0;
for (int l = tindex; l 20 < 4344; l 20) {
for (int u = tindex; u < tindex 20; u) {
// do something
}
tindex = tindex 20;
}
tindex沒必要,可以l直接使用l 20應該l =20
所以它變得像
for (int batch_begin = 0; batch_begin 20 < 4344; batch_begin = 20) {
for (int row = batch_begin; row < batch_begin 20; row) {
}
}
您還可以使用變數來保存批量大小并在兩個回圈中重用它
const int row_count = 4344;
const int batch_size = 20;
for (int batch_begin = 0; batch_begin batch_size < row_count; batch_begin = batch_size) {
for (int row = batch_begin; row < batch_begin batch_size; row) {
//do something
}
}
如果你想包括剩余的行(上面忽略它們),一個簡單的方法是std::min在第二個回圈中使用。
const int row_count = 4344;
const int batch_size = 20;
for (int batch_begin = 0; batch_begin batch_size < row_count; batch_begin = batch_size) {
for (int row = batch_begin; row < std::min(batch_begin batch_size, row_count); row) {
// do something
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/322613.html
