什么是數組
數組(array)是一個存儲了固定大小,同類型元素的集合。也就是說,數組就是一個由多個同類型元素按順序排列組成的一個集合。在程序執行的過程中我們經常會存儲很多數據,這時候就需要使用到數組。比如存儲100個學生的成績,每個學生的成績(假設都是整數)都是int類型的數值,這時候,把這些成績放到一個int sorce[100]的數組中,就可以更加方便地查看或操作這些學生的成績。
數組語法
聲明數組
//聲明數組 elementType arrayName[SIZE] //elementType可以是任何類型的數據類型,所有的數組成員都是這個類型的 //SIZE是大小,必須是大於0的整數 //上面的int sorce[100]就是一個所有成員都是int類型,數組大小為100(有100個成員)的
初始化數組
//初始化數組 //1. SIZE和Value elementType arrayName[SIZE] = {value1, value2, ..., valuen}; //2. 當有value時,可以省略SIZE,SIZE為value的個數n elementType arrayName[] = {value1, value2, ..., valuen};
數組元素賦值
注意:數組的下標是從0開始的,也就是說array[0]是數組array中的第一個元素,下標最大為SIZE-1
//數組賦值 arrayName[index] = value; //index是下標,最小為0,最大為SIZE-1
訪問數組
//訪問數組 arrayName[index];
處理數組
獲取數組長度
sizeof(array)/sizeof(array[0]); //sizeof()函數是所傳參數在內存中占的大小 //sizeof(array[0])表示里面一個元素的大小,sizeof(array)表示整個數組的大小
用輸入的值來初始化數組並輸入
#include <iostream> using namespace std; int main() { int sorce[10]; for (int i = 0; i < sizeof(sorce)/sizeof(sorce[0]); i++) { cout << "請輸入第" << i+1 << "個學生的成績(共十個):" ; cin >> sorce[i]; } for (int i = 0; i < sizeof(sorce)/sizeof(sorce[0]); i++) { cout << "第" << i+1 << "個學生的成績是:" << sorce[i] << endl; } return 0; }
運行結果:
復制數組
在C++中復制數組不能直接用=來操作(array1 = array2;),需要以循環的方式一個個元素復制
#include <iostream> using namespace std; const int SIZE = 5; int main() { int list[SIZE] = {1, 2, 3, 4, 5}; int myList[SIZE]; for (int i = 0; i < SIZE; i++) { myList[i] = list[i]; } for (int i = 0; i < SIZE; i++) { cout << "myList的第" << i+1 << "個元素:" << myList[i] << endl; } return 0; }
運行結果:
求數組中所有元素之和
#include <iostream> using namespace std; const int SIZE = 5; int main() { int list[SIZE] = {1, 2, 3, 4, 5}; int total = 0; for (int i = 0; i < SIZE; i++) { total += list[i]; } cout << "list數組中所有元素之和為:" << total << endl; return 0; }
運行結果:
數組作為函數參數(按址傳參)
#include <iostream> using namespace std; const int SIZE = 5;
//查看數組的第一個元素 void firstElement (int array[]) { cout << "The first element of array is " << array[0] << endl; } int main() { int list[SIZE] = {1, 2, 3, 4, 5}; firstElement(list); return 0; }
運行結果:
數組作為函數返回值
在C++中,不允許出現以數組類型為返回值的函數
//下面的函數頭是錯誤的,因為C++中不允許以數組為返回值 int[] funcation()
但是,我們可以在函數的形參中國添加一個數組來繞過這個限制。比如一個復制數組的函數:
#include <iostream> using namespace std; const int SIZE = 5; void arrayCopy (int array1[], int array2[]) { for (int i = 0; i < SIZE; i++) { array2[i] = array1[i]; } } int main() { int list[SIZE] = {1, 2, 3, 4, 5}; int myList[SIZE]; arrayCopy(list, myList); for (int i = 0; i < SIZE; i++) { cout << "myList的第" << i+1 << "個元素:" << myList[i] << endl; } return 0; }
運行結果: