简体   繁体   English

C ++数组初始化

[英]c++ array initialization

float minTime[7]={FLT_MAX};
    for(int i=0;i<7;i++)
        cout << "Min: " << minTime[i] << endl;

Why do I get in the following output : 为什么我得到以下输出:

Min: 3.40282e+038
Min: 0
Min: 0
Min: 0
...

Shoudln't all have the same value as the first one? 所有人的价值都应该与第一个相同吗? As it is refered here: C++ Notes 如此处所指: C ++注释

Your linked page says "...the unspecified elements are set to zero." 您的链接页面显示“ ...未指定的元素设置为零。”

This is correct; 这是对的; as such, only the first element in your array was specified to be FLT_MAX , the rest are initialized to zero. 这样,仅将数组中的第一个元素指定为FLT_MAX ,其余元素初始化为零。 If you want to set them all to the same value you can use a for-loop, or more succinctly: 如果要将它们都设置为相同的值,则可以使用for循环,或更简洁地说:

std::fill_n(minTime, 7, FLT_MAX);

As a warning, C++ is a hard language. 作为警告,C ++是一种硬语言。 This means lots of people have lots of misinformation, and this is especially easy to find on the internet. 这意味着很多人有很多错误信息,这在互联网上特别容易找到。 You'd be better off learning from a book on our list . 你最好从我们清单上书里学习。 (And yes, the ones not on our list are so because they too contain misinformation!) (是的, 不在我们列表中的是因为它们也包含错误信息!)

Shoudln't all have the same value as the first one? 所有人的价值都应该与第一个相同吗?

Nopes! 不! When an array is partially initialized the non-initialized array elements are value initialized ( zero-initialized in this case). 当对数组进行部分初始化时,将对未初始化的数组元素进行值初始化(在这种情况下为零初始化 )。

C++03 Section 8.5.1/7 C ++ 03第8.5.1 / 7节

If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5). 如果列表中的初始化程序少于聚合中的成员,则每个未显式初始化的成员都应进行值初始化 (8.5)。
[Example: [例:

 struct S { int a; char* b; int c; }; S ss = { 1, "asdf" }; 

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ] 初始化ss.a 1, ss.b用“ASDF”,和ss.c与表单INT(的表达式的值),即,0。]

不,只有第一个值使用提供的值初始化,其他值按照标准初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM