Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading