在C ++中将数组的所有元素初始化为一个默认值? [英] Initialization of all elements of an array to one default value in C++?

查看:739
本文介绍了在C ++中将数组的所有元素初始化为一个默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

代码

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:默认的初始化(如上所述)是否比遍历整个数组并分配值的常规循环要快?或者它执行相同的操作?

And 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 (来自<algorithm>):

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.

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

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