Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ for循环的两个代码之间有什么不同? #包括 #包括 使用名称空间std; 内部主(空) { 向量a={1,2,3,4,5}; 用于(自动和x:a) cout_C++_Reference_Auto_Range Based Loop - Fatal编程技术网

C++ for循环的两个代码之间有什么不同? #包括 #包括 使用名称空间std; 内部主(空) { 向量a={1,2,3,4,5}; 用于(自动和x:a) cout

C++ for循环的两个代码之间有什么不同? #包括 #包括 使用名称空间std; 内部主(空) { 向量a={1,2,3,4,5}; 用于(自动和x:a) cout,c++,reference,auto,range-based-loop,C++,Reference,Auto,Range Based Loop,您编写的代码的输出没有差异。但是,如果在循环中尝试更改x的值,则会有差异 #include <vector> #include <iostream> using namespace std; int main(void) { vector<int> a = {1, 2, 3, 4, 5}; for (auto x : a) cout << x << endl; } #包括 #包括 使用名称空间std;

您编写的代码的输出没有差异。但是,如果在循环中尝试更改
x
的值,则会有差异

#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<int> a = {1, 2, 3, 4, 5};
    for (auto x : a)
        cout << x << endl;
}
#包括
#包括
使用名称空间std;
内部主(空)
{
向量a={1,2,3,4,5};
用于(自动x:a)
x=0;
用于(自动x:a)

cout第一个是通过引用获取的,另一个是通过值获取的。在第一个示例中,您可以通过
x
更改
a
的元素。谢谢!您的答案非常有用。如果数据类型不是简单的int,而是某个大类,那么另一个区别就显而易见了。那么制作副本可能非常昂贵(=缓慢),而只引用引用总是很快的。@U.W.一个很好的例子来证明它(也许)将“auto”替换为“auto&”,副本就会消失。但是现在我手动添加了副本构造函数,这是否会改变编译器允许进行的优化?如果只调用const方法,可能允许一个微不足道的可复制对象优化副本?如何测试?或者可能是一个更好的证明,而不修改类const构造函数。检查临时地址。@bradgonesurfing如何测试?好吧,只编译到程序集级别并查看代码。就这么简单!:-)
#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<int> a = {1, 2, 3, 4, 5};
    for (auto x : a)
        cout << x << endl;
}
#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<int> a = {1, 2, 3, 4, 5};
    for (auto x : a)
        x = 0;
    for (auto x : a)
        cout << x << endl;
}
#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<int> a = {1, 2, 3, 4, 5};
    for (auto & x : a)
        x = 0;

    for (auto x : a)
        cout << x << endl;
}