# 陣列

``````資料型態 名稱[長度];
``````

``````int number[10];    // 宣告 10 個元素的整數陣列
double score[10];  // 宣告 10 個元素的浮點數陣列
char ascii[10];    // 宣告 10 個元素的字元陣列
``````

``````int number[10] = {0};
double score[10] = {0.0};
char ascii[10] = {'\0'};
bool flag[10] = {false};
``````

``````int number[5] = {0, 1, 2, 3, 4};
double score[5] = {87.0, 78.0, 99.5, 69.5, 82.5};
char ascii[5] = {'A', 'B', 'C', 'D', 'E'};
bool flag[5] = {false, true, false, true, false};
``````

``````#include <iostream>
using namespace std;

int main() {
constexpr int LEN = 10;
int number[LEN] = {0};

for(int i = 0; i < LEN; i++) {
cout << number[i] << " ";
}
cout << endl;

for(int i = 0; i < LEN; i++) {
number[i] = i;
}

for(int i = 0; i < LEN; i++) {
cout << number[i] << " ";
}
cout << endl;

return 0;
}
``````

``````0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
``````

``````#include <iostream>
using namespace std;

int main() {
int number[5] = {0, 1, 2, 3, 4};
int length = sizeof(number) / sizeof(number[0]);

for(int i = 0; i < length; i++) {
cout << number[i] << " ";
}
cout << endl;

return 0;
}
``````

C++ 17 的 `iterator` 提供了 `size` 函式，可以用來計算陣列大小，不過目前撰寫文件時使用的 g++ 編譯器需要加上 `-std=c++17` 才可以使用。

``````#include <iostream>
using namespace std;

int main() {
int number[5] = {0, 1, 2, 3, 4};

for(auto offset = begin(number); offset != end(number); offset++) {
auto n = *offset;
cout << n << " ";
}
cout << endl;

return 0;
}
``````

`offset` 是個指標（pointer），型態會是 `int*`，儲存的是位址，而 `*offset` 是取得儲存於該位址的值，因為之後才會談到指標，這邊就先用 `auto` 讓編譯器推斷型態，基於以上的原理，在 C++ 11 提供了 for range 語法，可用於循序走訪陣列的任務：

``````#include <iostream>
using namespace std;

int main() {
int number[5] = {0, 1, 2, 3, 4};

for(auto n : number) {
cout << n << " ";
}
cout << endl;

return 0;
}
``````

``````int number[] = {1, 2, 3};
double weight[] = {0.4, 3.2, 1.0, 4.2};
char ch[] = {'A', 'B'};
``````

``````constexpr int number[] = {1, 2, 3};
number[1] = 10; // error: assignment of read-only location 'number[1]'
``````

``````int arr1[5];
int arr2[5];
...
arr1 = arr2; // 錯誤！不能直接指定陣列給另一個陣列
``````

``````constexpr int LENGTH = 5;
int arr1[LENGTH];
int arr2[LENGTH];
...
for(int i = 0; i < LENGTH; i++) {
arr1[i] = arr2[i];
}
``````

``````#include <algorithm>
``````

``````#include <algorithm>
#include <iostream>

using namespace std;

int main() {
int number[] = {30, 12, 55, 31, 98, 11};

// 排序
sort(begin(number), end(number));
for(auto n : number) {
cout << n << " ";
}
cout << endl;

cout << "輸入搜尋值：";
int search = 0;
cin >> search;

int* addr = find(begin(number), end(number), search);
cout << (addr != end(number) ? "找到" : "沒有")
<< "搜尋值"
<< endl;

// 反轉
reverse(begin(number), end(number));
for(auto n : number) {
cout << n << " ";
}
cout << endl;

return 0;
}
``````

``````11 12 30 31 55 98

98 55 31 30 12 11
``````

`sort``find` 等函式，也可以作用在 `array``vector` 等，實際上，這些函式搭配函式的傳遞會更有效用，這之後都會談到。