使用一个默认值初始化 C++ 常规数组
我们可以非常简单地将整个数组初始化为 0,如下所示。
int arr[10] = {0};然而,使用上述方法无法将整个数组初始化为非 0 值,如下所示。
int arr[10] = {5};在上述示例中,只有第一个元素将初始化为 5。所有其他元素都初始化为 0。
可以使用 for 循环用非 0 的一个默认值初始化数组,如下所示。
for(i = 0; i<10; i++) {
arr[i] = 5;
}在上述示例中,所有数组元素都初始化为 5。
以下给出了演示上述所有示例的程序。
示例
#include <iostream>
using namespace std;
int main() {
int a[10] = {0};
int b[10] = {5};
int c[10];
for(int i = 0; i<10; i++) {
c[i] = 5;
}
cout<<"Elements of array a: ";
for(int i = 0; i<10; i++) {
cout<< a[i] <<" ";
}
cout<<"\n";
cout<<"Elements of array b: ";
for(int i = 0; i<10; i++) {
cout<< b[i] <<" ";
}
cout<<"\n";
cout<<"Elements of array c: ";
for(int i = 0; i<10; i++) {
cout<< c[i] <<" ";
}
cout<<"\n";
return 0;
}输出
上述程序的输出如下。
Elements of array a: 0 0 0 0 0 0 0 0 0 0 Elements of array b: 5 0 0 0 0 0 0 0 0 0 Elements of array c: 5 5 5 5 5 5 5 5 5 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP