基于范围的堆分配数组的循环 [英] Range based for loop for heap allocated arrays

查看:76
本文介绍了基于范围的堆分配数组的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码,该代码将准确提示success三遍:

Consider the following code which will cout success exactly three times:

int arr [3];

for(int& value : arr )
    std::cout << "success" << std::endl;

如果我尝试在堆上分配数组,则会出现问题.该代码无法编译:

If I try to allocate array on the heap, there are problem. This code doesn't compile:

int* ptr = new int[3];

for(int& value : *ptr )
    std::cout << "success" << std::endl;

由于指针已被取消引用,因此类型应相同.所以我有一些问题:

Since the pointer was dereferenced, the types should be the same. So I have some questions:

  • 当我从两个表达式中的硬件询问时,根本的区别是什么.我想了解为什么后者没有意义.
  • 我可以做一点零钱吗?

推荐答案

如果可见声明包含元素数量,即原始数组int arr[3]int* prt,则原始数组仅支持基于范围的语法.在第二种情况下.在第一种情况下,给出了此信息(但如果可能的话,您仍应首选std::array),但在第二种情况下,则不会在堆上分配内存,并且有关大小的信息也消失了.如果您只使用std::array而不是原始数组,则可以避免这种情况.

A raw array only supports the range-based for syntax if the visible declaration includes the number of elements, i.e. int arr[3] in the first case and int* prt in the second case. In the first case this is given (but still you should prefer std::array if possible), but not in the second case you allocate memory on the heap and the information about the size is gone. You can circumvent this, if you simply use std::array rather than the raw array.

由于指针已被取消引用,因此类型应相同.

Since the pointer was dereferenced, the types should be the same.

仔细研究一下,原因是,在第一种情况下,您有一个数组,在第二种情况下,您有一个指针,即使相同的类型也

Taking a closer look under the hood, the reason for this is, that in the first case you have an array and in the second case you have a pointer, which is NOT even the same type.

这种对指针和数组相等性的误解一直在C ++教程中传播,但这是错误的.这可能是由于以下事实:将数组传递给带有该类型指针的函数时,数组 decays 指向一个指针,即 array-decay .

This misinterpretation of pointer and array equaliuty keeps to be broadcasted over C++ tutorials, but this is wrong. This might be due to the fact, that when passing an array to a function taking a pointer of that type, the array decays to a pointer, known as array-decay.

我可以做一点改动吗

Can I make it work with a small change

是的,可以.使用std::arrayst::vector会使它看起来像std::array

Yes you can. Use std::array or st::vector which will make it look like that for std::array:

#include <iostream>
#include <array>

int main()
{
    std::array<int, 3>* ptr = new std::array<int, 3>;

    for(int& value : *ptr )
        std::cout << "success" << std::endl;
}

为简洁起见,我没有包括您应该经常删除的指针.

For brevity I did not include the delete for the pointer which you should always do.

但是,如果在堆上分配内存,则几乎总是最好使用std::vector,因为将自动处理释放.该程序将显示为:

However, if you allocate memory on the heap, it is almost always best to use std::vector as deallocation will be taken care for automatically. The program would than read:

#include <iostream>
#include <vecor>

int main()
{
    std::vector<int> vec(3);

    for(int& value : vec)
        std::cout << "success" << std::endl;
}

这篇关于基于范围的堆分配数组的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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