简体   繁体   English

在 foreach 循环中将变量声明为 i vs &i

[英]Declaring variable as i vs &i in the foreach loop

Why do these loops give the same output:为什么这些循环给出相同的 output:

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

They both give the same output:它们都给出相同的 output:

2 3 4 2 3 4

2 3 4 2 3 4

When declaring the foreach loop variable, shouldn't adding ampersand make the variable take the references of the values in the array, and printing i make it print the references.在声明 foreach 循环变量时,不应添加 & 使变量获取数组中值的引用,并打印 i 使其打印引用。 What is happening here?这里发生了什么?

By print the references I meant something like this code prints:通过打印参考我的意思是这样的代码打印:

for(auto i: ar)
    cout<<&i<<" ";

Output: Output:

0x61fdbc 0x61fdbc 0x61fdb 0x61fdbc 0x61fdbc 0x61fdb

The ampersand operator has many purposes. & 运算符有很多用途。 These two of the many are hard to recognize, namely the & infront of a variable in a declaration ( such as int& i ( or int &i , same thing ) ), and the & infront of a variable not in a declaration, such as cout << &i .这两个很难识别,即声明中变量的& infront(例如int& i (或int &i ,相同的东西)),以及不在声明中的变量的& infront,例如cout << &i .

Try these and you will get a better understanding.试试这些,你会得到更好的理解。

for (auto i : ar)
    cout << i << " "; // 2 3 4 // element of ar
    
for (auto &i : ar)
    cout << i << " "; // 2 3 4 // element of ar

for (auto i : ar)
    cout << &i << " "; // address of local variable i (probably same address)
    
for (auto &i: ar)
    cout << &i << " "; // address of elements of ar (increasing addresses)

The results are the same because in the first loop you copy the variable's value in a new variable i and print its value.结果是相同的,因为在第一个循环中,您将变量的值复制到新变量i中并打印其值。 (Additional RAM allocated) (分配了额外的 RAM)

In the second loop you access the value of the current element from the memory by assigning its address to i .在第二个循环中,您通过将其地址分配给i来访问 memory 中当前元素的值。 (No additional RAM allocated) (没有分配额外的 RAM)

On the other side:另一方面:

cout<<&i<<" ";

causes printing the address of i .导致打印i的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM