C++ Arrays
Inizialization
// Inizialization samples: int foo [5]; int foo [5] = { 16, 2, 77, 40, 12071 }; int bar [5] = { 10, 20, 30 }; int bar [5] = { }; // They are equivalent int foo[] = { 10, 20, 30 }; int foo[] { 10, 20, 30 };
Store – Access
// Store foo [2] = 75; // Access x = foo[2];
Operations
foo[0] = a; foo[a] = 75; b = foo [a+2]; foo[foo[a]] = foo[2] + 5;
Multidimensional Arrays
Multidimensional arrays can be described as “arrays of arrays”.
int jimmy [3][5]; // is equivalent to int jimmy [15]; // (3 * 5 = 15)
Arrays as parameters
At some point, we may need to pass an array to a function as a parameter.
// arrays as parameters #include <iostream> using namespace std; void printarray (int arg[], int length) { for (int n=0; n<length; ++n) cout << arg[n] << ' '; cout << '\n'; } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); }
The result is:
5 10 15
2 4 6 8 10
Library Array
C++ provides an alternative array type as a standard container.
#include <iostream> #include <array> using namespace std; int main() { array<int,3> myarray {10,20,30}; for (int i=0; i<myarray.size(); ++i) ++myarray[i]; for (int elem : myarray) cout << elem << '\n'; }
Reference: http://www.cplusplus.com/doc/tutorial/arrays/