Home »
C++ STL
Array in C++ Standard Template Library (STL) with its common functions
C++ STL std::array class with its common functions: Here, we will learn about the array class with its common functions with Example in C++ Standard Template Library.
Submitted by IncludeHelp, on September 01, 2018
C++ STL Array Class
"array" is a container in C++ STL, which has fixed size, which is defined in "array" header.
Declaration
array <data_type, size> array_name = {initializer_list};
Example:
array<int,5> values {10, 20, 30, 40, 50};
Array Class's Common Functions
- array::operator[] - Gets and sets a reference to an element based on given index.
- array.empty() - Returns true if array is empty
- array.size() - Returns the total number of elements in the array
- array.front() - Return the first element
- array.back() - Returns the last element
- array.at(index) - Returns the element from given index
- array.begin() - Returns the reference pointing to the first element
- array.end() - Returns the reference punting to the last element
Example of C++ STL Array Class
#include <array>
#include <iostream>
using namespace std;
int main() {
// array declaring and initialization
array<int, 5> arr = {10, 20, 30, 40, 50};
// checking array is empty or not by using empty()
if (arr.empty())
cout << "Array is empty!!!" << endl;
else
cout << "Array is not empty!!!" << endl;
// Array functions
cout << "size: " << arr.size() << endl;
cout << "first element: " << arr.front() << endl;
cout << "last element: " << arr.back() << endl;
cout << "0th element: " << arr.at(0) << endl;
cout << "3rd element: " << arr.at(3) << endl;
// printing all array elements are: ";
for (auto i = arr.begin(); i != arr.end(); i++) cout << *i << " ";
cout << endl;
return 0;
}
Output
Array is not empty!!!
size: 5
first element: 10
last element: 50
0th element: 10
3rd element: 40
10 20 30 40 50
Reference: C++ std::array