0

I have come across the solution to print the 2 D array using C++.

The ans was to use auto keyword:

for eg:

double nut_torques[4][5]; // this is my array with type double 
for (auto& rows : nut_torques) 
{
    for (auto cols : rows) 
    {
       std::cout << cols << " ";
    }
    std::cout << std::endl;
}

But can anyone tell me what if I don't want to use aut?

For example, if there is 1 D array then using double(since my type is double) works:

for (double rows : array) {
}

I tried following for 2D array, but this time double worked only for inner foreach:

for (auto& rows : nut_torques) 
{
    for (**double** cols : rows) 
    {
       std::cout << cols << " ";
    }
    std::cout << std::endl;
}

But the following did not work for me, when I tried adding double for both inner and outer foreach:

for (**double** rows : nut_torques) 
{
    std::cout << rows<<std::endl;

    for (**double** cols : rows) 
    {
        std::cout << cols << " ";
    }
    std::cout << std::endl;
}

May I know the reason why we can't use double in outer foreach and what if I don't want to use auto then what shall I use there.

Also, if we std::cout array variable, then we get address to the first index. Then how come for single foreach this line works:

for(double val: arrVariable)

Does foreach automatically dereferences the arrayVariable and does it automatically increments it?

JeJo
  • 30,635
  • 6
  • 49
  • 88
Chinmay
  • 11
  • 2

1 Answers1

1

The outer for loop does not iterate over doubles, but rather over rows, which are saved as array. When you cout the array variable, you are basically printing the pointer, since array is saved as a pointer to the first element.

I believe this for loop uses iterators like std::begin and std::end to traverse the array. This is why you need the type shown below instead of double *row in the outer for loop, since you cannot call std::begin using a pointer.

This is how you would write it without auto. You have to write out the correct types by hand. The variables of outer for are references to arrays and the inner has doubles.

for (double (&row)[5] : nut_torques) {
    for (double value : row) {
        std::cout << value << " ";
    }
    std::cout << std::endl;
}

Basically the type of the outer loop is the same as type of nut_torques[0] and nut_torques[0][0] for the inner loop.

Blaz
  • 123
  • 6
  • Hello,@Blaz, this answer works, thanks. Can you tell me any book from which I will know some small points like this which you have given. – Chinmay Jun 10 '23 at 17:12
  • Regarding C++ I only read C++ Primer. It does explain iterators as well. The main concept here is also present in other languages like Java or Python. The outer loop iterates over the first dimension (elements are arrays) and the inner one over the second dimension (values itself). – Blaz Jun 10 '23 at 17:28