如何在 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP