The following table shows some commonly used array APIs:
|
API |
Description |
|
at( int index ) |
This returns the value stored at the position referred to by the index. The index is a zero-based index. This API will throw an std::out_of_range exception if the index is outside the index range of the array. |
|
operator [ int index ] |
This is an unsafe method, as it won't throw any exception if the index falls outside the valid range of the array. This tends to be slightly faster than at, as this API doesn't perform bounds checking. |
|
front() |
This returns the first element in the array. |
|
back() |
This returns the last element in the array. |
|
begin() |
This returns the position of the first element in the array |
|
end() |
This returns one position past the last element in the array |
|
rbegin() |
This returns the reverse beginning position, that is, it returns the position of the last element in the array |
|
rend() |
This returns the reverse end position, that is, it returns one position before the first element in the array |
|
size() |
This returns the size of the array |
The array container supports random access; hence, given an index, the array container can fetch a value with a runtime complexity of O(1) or constant time.
The array container elements can be accessed in a reverse fashion using the reverse iterator:
#include <iostream>
#include <array>
using namespace std;
int main () {
array<int, 6> a;
int size = a.size();
for (int index=0; index < size; ++index)
a[index] = (index+1) * 100;
cout << "\nPrint values in original order ..." << endl;
auto pos = a.begin();
while ( pos != a.end() )
cout << *pos++ << "\t";
cout << endl;
cout << "\nPrint values in reverse order ..." << endl;
auto rpos = a.rbegin();
while ( rpos != a.rend() )
cout << *rpos++ << "\t";
cout << endl;
return 0;
}
We will use the following command to get the output:
./a.out
The output is as follows:
Print values in original order ...
100 200 300 400 500 600
Print values in reverse order ...
600 500 400 300 200 100