Initialization of all elements of an array to one default value in C++?(将数组的所有元素初始化为C++中的一个默认值?)
问题描述
C++ Notes: Array Initialization 有一个很好的列表数组的初始化.我有一个
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++中的一个默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将数组的所有元素初始化为C++中的一个默认值?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
