【发布时间】:2021-03-16 13:18:34
【问题描述】:
为什么这些循环给出相同的输出:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> ar = {2, 3 ,4};
for(auto i: ar) //this line changes in the next loop
cout<<i<<" ";
cout<<"\n";
for(auto &i: ar) //i changed to &i
cout<<i<<" ";
}
它们都给出相同的输出:
2 3 4
2 3 4
在声明 foreach 循环变量时,不应添加 & 使变量获取数组中值的引用,并打印 i 使其打印引用。这里发生了什么?
通过打印引用我的意思是这样的代码打印:
for(auto i: ar)
cout<<&i<<" ";
输出:
0x61fdbc 0x61fdbc 0x61fdb
【问题讨论】:
-
你认为“打印参考文献”应该打印什么?
-
现在在这两种情况下测试
std::cout << &i << " ";。 -
引用不是指针,它们是别名。通过打印引用,您可以打印被引用的实际值
-
@Jarod42,我做到了。现在它们都打印以 0x 开头的值...你能解释一下发生了什么吗?
-
@IWonderWhatThisAPIDoes 你能解释一下别名是什么意思吗?也许将我引导到一个资源,在那里我可以了解更多关于此的信息..
标签: c++ loops for-loop foreach ampersand