我如何使用 C++ 中的陣列?
陣列是一系列同類型元素,它們位於連續的記憶體位置,可以透過向唯一識別符號新增索引來單獨引用它們。要在 C++ 中使用陣列,你需要先宣告它,例如,
int arr[10];
這將宣告一個大小為 10 的 int 型別的陣列。它可以在連續記憶體中儲存 10 個整數。要引用其任何元素,你需要使用陣列訪問運算子,併為其提供你想要訪問的元素的索引。C++ 陣列的索引從 0 開始。因此,在陣列 arr 中,我們有 10 個索引為 0、1、2、... 9 的元素。要訪問第三個元素(即索引為 2 的元素),你可以寫:arr[2]。
你可以像 − 一樣在迴圈中訪問所有元素
#include<iostream>
using namespace std;
int main() {
int arr[10];
// Create a loop that starts from 0 and goes to 9
for(int i = 0; i < 10; i++) {
cin >> arr[i]; // Input the ith element
}
// Print the elements you took as input
for(int i = 0; i < 10; i++) {
cout << arr[i] << endl; // Input the ith element
}
}輸出
它將產生輸出 −
1 5 -6 45 12 9 -45 12 3 115
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP