在C++中使用 auto 关键字

Using the auto keyword in C++

本文关键字:auto 关键字 C++      更新时间:2023-10-16

我只是使用一个简单的代码,使用 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;
}  

我无法弄清楚为什么 PArray[i][j] 中的值,给定 [i][j] 在边界内,导致值为零。

此外,编译器抱怨说,它说">

begin"没有在范围内声明,然后指向for循环中的数组自动变量,也指向同一个变量,说"end"没有声明。

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

for(auto Array: PArrays)为您提供PArrays中每个元素的值副本。因此,您在Array中所做的任何更改都不会反映在原始容器PArrays中。

如果您希望Array成为对PArrays元素的引用,请使用

for(auto& Array: PArrays)

相反。