Basic Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| int un_init_arr[5];
for (int & ele: un_init_arr) { cout << "before assign = " << ele << "\n";
ele = 0;
cout << "after assign = " << ele << "\n"; }
int init_arr[5] = {1,2,3,4,5}; int auto_count_arr[] = {6,7,8};
cout << "should be 3 = " << init_arr[2] << "\n";
cout << "out of bound access = " << init_arr[6] << "\n";
for (const int & ele: init_arr) { cout << ele << "\n"; } for (const int & ele: auto_count_arr) { cout << ele << "\n"; }
cout << "length of array is " << sizeof(auto_count_arr) / sizeof(*auto_count_arr) << "\n";
|
Heap allocation
1 2 3 4 5 6 7 8 9 10 11
|
int *heap_arr = new int[5];
for (int & ele: *heap_arr) ele = 4;
delete[] heap_arr;
|
array class
This is a syntactic sugar on top of fixed-size arrays, with no performance overhead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <array>
array<int, 5> un_init_arr;
un_init_arr.fill(1);
for (const int & ele: un_init_arr) cout << ele << "\n";
array<int, 5> init_arr = {1,2,3,4,5};
cout << "should be 3 = " << init_arr[2] << "\n";
cout << "out of bound access = " << init_arr[6] << "\n";
cout << "out of bound access = " << init_arr.at(6) << "\n";
init_arr.front() = 10; cout << "first element of the array is " << init_arr.front() << "\n";
init_arr.back() = 11; cout << "last element of the array is " << init_arr.back() << "\n";
for (const int & ele: init_arr) cout << ele << "\n";
for (auto i = 0; i < init_arr.size(); ++i) cout << init_arr.at(i) << "\n";
for (auto ele = init_arr.begin(); ele != init_arr.end(); ++ele) cout << *ele << "\n";
|
Take Home
If I need a fixed-size array in C++, I will definitely go with array class.
If I want to access an element, I will always go with .at()
.
I see using []
in C++ program to be evil.
I also guess that the gap between []
and array
is due to the need for maintaining compatibility between C and C++
Refereneces