Home > OS >  Nested loops bounds
Nested loops bounds

Time:10-17

I have a 2D_array with size [4344][20], for some reasons I want to transfer between the first 20 rows, then move to the next 20 rows, and then to next next 20 rows... etc. until reach to the last row which is row 4343.

Do I do that correct?

my code:

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;
    }
}

CodePudding user response:

This is how I would do it with C (from C 11 onward). Though I probably wouldn't even use the array directly but wrap it in a class and pass the class around. (And I would name the class after WHAT it is representing, the array is just the HOW). I would also make any operations on the array member functions of the class.

So my question is what does the array represent?

#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);
}

CodePudding user response:

/// 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 is not necessary, you can use l directly
  • l 20 should be l =20

so it becomes something like

for (int batch_begin = 0; batch_begin   20 < 4344; batch_begin  = 20) {
   for (int row = batch_begin; row < batch_begin   20;   row) {
   }
}



you can also use a variable to hold batch size and reuse it in both loop

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 
   }
}

If you want to include the remained rows (the above ignore them), a simple way is use std::min on second loop.

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
   }
}
  • Related