C++ array std::get
The std::get
function retrieves the element at the specified index from a std::array
. It is a template function and provides a type-safe way to access elements by their index. The index must be a compile-time constant, and bounds checking is not performed.
Syntax of std::get
template<std::size_t I, class T, std::size_t N>
constexpr typename std::array<T, N>::reference get(std::array<T, N>& arr) noexcept;
template<std::size_t I, class T, std::size_t N>
constexpr typename std::array<T, N>::const_reference get(const std::array<T, N>& arr) noexcept;
Parameters
Parameter | Description |
---|---|
I | A compile-time constant representing the index of the element to access. |
arr | The std::array object from which the element is retrieved. |
Return Value
Returns a reference to the element at the specified index I
. If the array is const
, the returned reference is also const
.
Exceptions
The std::get
function does not throw exceptions. However, accessing an out-of-bounds index results in a compilation error.
Examples for std::get
Example 1: Accessing Elements Using std::get
This example demonstrates how to access elements of a std::array
using std::get
:
#include <iostream>
#include <array>
int main() {
std::array<int, 5> arr = {10, 20, 30, 40, 50};
std::cout << "Element at index 0: " << std::get<0>(arr) << std::endl;
std::cout << "Element at index 2: " << std::get<2>(arr) << std::endl;
std::get<4>(arr) = 100; // Modify the element at index 4
std::cout << "Modified element at index 4: " << std::get<4>(arr) << std::endl;
return 0;
}
Explanation:
- A
std::array
namedarr
is initialized with the elements{10, 20, 30, 40, 50}
. - The
std::get<I>(arr)
function is used to retrieve the element at indexI
, whereI
is a compile-time constant. - The element at index
4
is modified to100
usingstd::get
. - The modified value is printed to confirm the change.
Output:
Element at index 0: 10
Element at index 2: 30
Modified element at index 4: 100
Example 2: Compile-Time Error for Invalid Index
This example demonstrates the compile-time error when trying to access an invalid index:
#include <iostream>
#include <array>
int main() {
std::array<int, 3> arr = {1, 2, 3};
std::cout << std::get<3>(arr) << std::endl; // Index 3 is out of bounds
return 0;
}
Explanation:
Attempting to access index 3
in a std::array
of size 3 results in a compile-time error, as std::get
requires the index to be within bounds.
Output:
In file included from main.cpp:2:
/usr/include/c++/11/array: In instantiation of ‘constexpr _Tp& std::get(std::array<_Tp, _Nm>&) [with long unsigned int _Int = 3; _Tp = int; long unsigned int _Nm = 3]’:
main.cpp:7:29: required from here
/usr/include/c++/11/array:363:26: error: static assertion failed: array index is within bounds
363 | static_assert(_Int < _Nm, "array index is within bounds");
| ~~~~~^~~~~