【问题标题】:What is the difference between for(auto& x:A) and for(auto &x:A) in C++ [duplicate]C ++中的for(auto&x:A)和for(auto&x:A)有什么区别[重复]
【发布时间】:2020-04-19 03:16:44
【问题描述】:

我有一个 int 类型数组,我想使用基于范围的 for 循环来引用它的值,但是我找不到使用 for(auto& x:A) 和 for(auto &x:A) 之间的区别。两者在我的编译器中都有效并给出相同的输出。有区别吗?

这是我正在使用的代码和输出:

#include "pch.h"
#include <iostream>
using namespace std;

int main()
{
    int A[10] = {0,1,2,3,4,5,6,7,8,9};

    //Using any of the two following lines, there seems to be no diference in the output.
    //for (auto& x : A) x=1;
    //for (auto &x : A) x=1;

    for (auto x : A) cout << x << " ";
} 

输出是: 1 1 1 1 1 1 1 1 1 1

【问题讨论】:

标签: c++ foreach reference


【解决方案1】:

但我找不到使用 for(auto& x:A) 和 for(auto &x:A) 之间的区别

没有区别。

与指针类型相同:int* pint *p 是相同的东西。

两种风格都是正确的。但是,请参阅这表明 &amp;* 更接近变量名称可能会更好(即更喜欢后一种样式):

https://www.quora.com/Where-should-I-put-the-asterisk-for-pointers-in-C++-Is-it-int-ptr-int--ptr-or-int-*ptr

根据我与许多客户的经验,无论大小,还有几个 不同的编码标准,绝大多数附加 变量名的星号(即 int *ptr)

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 2020-07-31
    • 1970-01-01
    • 2014-02-17
    相关资源
    最近更新 更多