一个正常的数组初始化一个默认值 [英] Initialization of a normal array with one default value

查看:163
本文介绍了一个正常的数组初始化一个默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++注:阵列初始化过有一个很好的列表阵列的初始化。我有一个

C++ Notes: Array Initialization has a nice list over initialization of arrays. I have a

int array[100] = {-1};

希望它是充满-1的,但它不是,只有第一个值,其余为0的混合随机值。

expecting it to be full with -1's but its not, only first value is and the rest are 0's mixed with random values.

在code

int array[100] = {0};

工作得很好,并设置每个元素为0。

works just fine and sets each element to 0.

我缺少的是在这里..不能在一个初始化如果该值不为零?

What am I missing here.. Can't one initialize it if the value isn't zero ?

2:是默认的初始化(如上)不是通过整个阵列通常的循环更快,分配一个值还是它做同样的事情。

2: Is the default initialization (as above ) faster than the usual loop through the whole array and assign a value or does it do the same thing?

推荐答案

使用您所使用的语法:

int array[100] = {-1};

说的第一个元素设置为 1 剩下的 0 ,因为所有的元素略设置到 0

says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

在C ++中,将它们全部设置为 1 ,您可以使用类似的 的std :: fill_n (从<&算法GT; ):

In C++, to set them all to -1, you can use something like std::fill_n (from <algorithm>):

std::fill_n(array, 100, -1);

在便携式C,你必须推出自己的循环。有编译器的扩展,也可以依靠实现定义的快捷方式,如果这是可以接受的。

In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

这篇关于一个正常的数组初始化一个默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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