Using auto keyword in C ++

I just use simple code that uses auto:

double **PArrays = new double*[3];

count = 0;
for(auto Array: PArrays)
    {
        Array = new double[6];
        for(int i{}; i < 6; i++)
        {
            if(count == 0)
            {

                Array[i] = i;
                std::cout<<"The value of Array i is: "<<Array[i]<<std::endl;
                std::cout<<"The value of PArray is: "<<PArrays[count][i];
            }
            else if(count == 1)
            {
                Array[i] = i * i;
            }
            else
            {
                Array[i] = i * i * i;               
            }
        }
        count += 1;
    }  

      

I can't figure out why the values ​​in PArray [i] [j], given that [i] [j] are within bounds, results in a value of zero.

Also, the compiler complains, it says "begin" was not declared in scope, and then points to the automatic variable Array in the for loop, also points to the same variable where "end" was not declared .:

for(auto Array: PArrays)
    {
        for(auto x: Array)
        {
            std::cout<<"The value is: "<<x;
        }
        std::cout<<std::endl;
    }

      

+3


source to share


1 answer


for(auto Array: PArrays)

gives you a copy of the value of each item in PArrays

. Therefore, any changes you make to Array

will not show up in the original container PArrays

.

If you want to be Array

a link to an element PArrays

use



for(auto& Array: PArrays)

instead.

+8


source







All Articles