cpp reference array
The std::array
is a container that encapsulates fixed-size arrays. Here are the steps for using std::array
in C++:
Include the Header File: Begin by including the
<array>
header file in your code to use thestd::array
container.```cpp
include
```
Declare a
std::array
: Define astd::array
specifying the data type and size. For example:cpp std::array<int, 5> myArray;
This line declares an array named
myArray
containing integers and has a size of 5.Initialize
std::array
elements: You can initialize the elements of thestd::array
upon declaration or later using curly braces{}
:cpp std::array<int, 5> myArray = {1, 2, 3, 4, 5};
Alternatively, you can set individual elements after declaration:
cpp myArray[0] = 10; myArray[1] = 20; // ...
Accessing
std::array
Elements: Access elements using the subscript ([]
) operator just like regular arrays:cpp int element = myArray[2]; // Accesses the third element of the array.
Iterating Through
std::array
: Use iterators or range-based for loops to traverse throughstd::array
elements:cpp for (const auto& elem : myArray) { // Use elem }
Size of
std::array
: Retrieve the size of thestd::array
using itssize()
member function:cpp size_t arraySize = myArray.size();
This returns the number of elements in the array.
Other Member Functions:
std::array
provides other member functions likeat()
,front()
,back()
, etc., for specific operations on the array elements.
Using these steps, you can effectively declare, initialize, access, and manipulate elements within a std::array
in C++.