方法,用来初始化数组容器中,C ++ [英] Ways to initilize array container in C++

查看:141
本文介绍了方法,用来初始化数组容器中,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我道歉,如果我不正确,或者如果我问一个显而易见的问题使用的术语。我最近才开始学习C ++)

(I apologize if I do not use terminology correctly or if I am asking an obvious question. I only recently started learning C++)

我见过的最例子在线使用下面的方法来初始化数组容器:

I've seen that the most examples online use the following way to initialize array container:

std::array<int,3> myarray = { 2, 16, 77 };

不过,我试图做以下内容:

But I tried doing the following:

std::array<int,3> myarray;

myarray[0] = 2;
myarray[1] = 16;
myarray[2] = 77;

似乎是工作了。首先是方法preferred在第二或第二个根本不正确?

Seems to be working too. Is first method preferred over the second or is the second one simply incorrect?

推荐答案

的std ::阵列&LT; INT,3&GT; myArray的= {2,16,77}; 优越:


  1. 这是更加清晰

  1. It's clearer

myarray中是从来没有在一个不确定的状态。随着的std ::阵列&LT; INT,3&GT; myArray的; ,该元素是默认初始化,这意味着的未初始化的作为默认初始化一个 INT 是离开它未初始化。因此,对设置它们的值之前回读元素的行为是不确定的。

myarray is never in an undefined state. With std::array<int,3> myarray;, the elements are default-initialised, which means uninitialised as the default initialisation for an int is to leave it uninitialised. So the behaviour on reading back elements prior to setting their values is undefined.

这是的可能的速度更快。 (编译器可能会优化你已经完成它的第一种方式的第二种方式)。

It's possibly faster. (The compiler might optimise the second way you've done it to the first way).

由于C ++ 11的我认为第二个方式是错误的。

Since C++11 I would regard the second way as being wrong.

这篇关于方法,用来初始化数组容器中,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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