加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11阵列怎么能不存储它的大小?

发布时间:2020-12-16 06:46:15 所属栏目:百科 来源:网络整理
导读:从 cplusplus.com开始: Internally,an array does not keep any data other than the elements it contains (not even its size,which is a template parameter,fixed on compile time). 我理解这意味着使用数组类似于在同一范围内使用int []和sizeof.但这
从 cplusplus.com开始:

Internally,an array does not keep any data other than the elements it contains (not even its size,which is a template parameter,fixed on compile time).

我理解这意味着使用数组类似于在同一范围内使用int []和sizeof.但这段代码是有效还是依赖于未定义的行为?

class A {
    array<int,10> arr;
    void setArr() {
        for (int& i : arr)
            i = 42;
    }
    void printArr() {
        for (int i : arr)
            cout << i << endl;
    }
};

编译器如何知道何时停止foreach而不将数组大小存储在堆或堆栈上?我运行它,代码工作.

解决方法

它说的更多,回复在你的报价中:

[…] not even its size,fixed on compile time […]

例如,以下代码也是合法的:

template<int N>
struct C {
    int size() { return N; }
};

正如你所看到的,这里我们做同样的事情并且N不会被保留,但它是一个模板参数,在编译时固定.

这对于模板化类std :: array是有效的,它接受定义其大小的模板参数.因此,大小在编译时是已知的(并且是固定的),并且它隐式地是生成类型的一部分,即使在运行时没有保留额外的空间.

编辑(相应的评论)

当然,通过简单地调用其中一个方法,您无法在运行时更改此类数组的大小.如here所述:

std::array is a container that encapsulates fixed size arrays.

此外,动态更改其大小没有意义,因为它将不再与定义实际大小的模板参数保持一致.因此,响应显然是:不,你不能改变它的大小(当然,即使你可以使用该数组来填充另一个具有不同大小的数组).

但是,你有很多好处:

The struct combines the performance and accessibility of a C-style array with the benefits of a standard container,such as knowing its own size,supporting assignment,random access iterators,etc.

由您来决定是否值得使用它而不是简单的C风格数组.这主要取决于你所面临的问题,所以我不能这么说.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读