c++for-looprange-based-loop

Multidimensional arrays


I was curious about why we go through a multidimensional array this way

for (auto& row : mat1)
    {
        for (int& elements : row)
        {
            cin >> elements;
        }
    }

Why do we use &(pass by ref) when we make a temp variable called elements that goes through the rows and gets each value. aswell as the & in the for (auto& row : mat1) Can someone explain this whole part with every detail please ?

using namespace std;
int main()
{
    const int row{ 3 }, col{ 3 };
    array<array<int, col>, row > mat1;
    cout << "Enter matrix 1 elements: ";
    for (auto& row : mat1)
    {
        for (int& elements : row)
        {
            cin >> elements;
        }
    }
    for (auto& row : mat1)
    {
        for (int& elements : row)
            cout << elements << "  ";
        cout << endl;
    }
    

Solution

  • If you don't use references, then you will make copies of the data.

    And if you make a copy (iterate by value) rather than using references, you will only modify the local copy, not the original data.

    This is for the input loop of course, where you have

    cin >> elements;
    

    In the output loop there's no need for references for the int elements themselves, but I recommend using const references for the arrays since otherwise you make a copy which could be expensive.

    So in the output loop to:

    for (auto const& row : mat1)
    {
        for (auto element : row)
        {
            std::cout << element;
        }
    }