C ++ for循环范围与常规for循环不同 [英] C++ range for loop different than regular for loop

查看:56
本文介绍了C ++ for循环范围与常规for循环不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与常规for循环相比,for循环的范围提供了不同的地址.如何使用增强的for循环?

The range for loop is providing different addresses compared to the regular for loop. How can I use enhanced for loops?

iArr 地址: 011bf7cc

循环地址的范围: 011bf79c 011bf79c 011bf79c

常规的循环地址: 011bf7cc 011bf79c 011bf7d4

#include <iostream>
#include "TestingConstructors.h"
#include <Windows.h>

using namespace std;


int main() {
     int i, j, *i1, *i2;
     i = 1;
     j = 3;
     i1 = &i;
     i2 = &j;
     *i1 = 2;
     int iArr[3] = { 1,2,3 };
     cout << &iArr << endl << endl;
     for (int i : iArr)
          cout << &i << " ";
     cout << endl << endl;
     for (int i = 0; i < ARRAYSIZE(iArr); i++)
          cout << &iArr[i] << " ";
     system("pause");
    return 0;
}

推荐答案

没有增强循环" 这样的东西.这是"范围循环":

There is no such thing as an "enhanced for loop". This is a "range-for loop":

for (int i : iArr)
      cout << &i << " ";

它为您提供了一个不同的地址,因为 int i:iArr 正在创建 iArr 的每个元素的副本并将其分配给 i .

It gives you a different address because int i : iArr is creating a copy of every element of iArr and assigning it to i.

如果要引用原始元素,则应使用

If you want to refer to the original elements, you should use

for (int& i : iArr)
      cout << &i << " ";

这篇关于C ++ for循环范围与常规for循环不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆