使用一個預設值初始化 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

更新於: 2020-06-26

16K+ 瀏覽次數

啟動您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.