溫馨提示×

常量數(shù)組在C++中的初始化方法有哪些

c++
小樊
82
2024-09-11 17:50:07
欄目: 編程語言

在 C++ 中,常量數(shù)組(const array)可以通過以下幾種方法進(jìn)行初始化:

  1. 使用花括號 {} 初始化:
const int arr[] = {1, 2, 3, 4, 5};
  1. 使用 std::initializer_list 初始化:
#include<initializer_list>

int main() {
    const std::initializer_list<int> arr = {1, 2, 3, 4, 5};
}
  1. 使用 std::array 初始化:
#include<array>

int main() {
    const std::array<int, 5> arr = {1, 2, 3, 4, 5};
}

注意:在這些示例中,我們使用了 const 關(guān)鍵字來創(chuàng)建一個常量數(shù)組。這意味著數(shù)組的內(nèi)容在初始化后不能更改。如果需要創(chuàng)建一個非常量數(shù)組,只需刪除 const 關(guān)鍵字即可。

0