std::array is a C++ Standard Library container that provides a fixed-size array with additional functionalities compared to traditional C-style arrays. It is part of the C++ Standard Library and is defined in the header. std::array ensures type safety, bounds checking, and other useful member functions that make it a safer and more convenient alternative to raw arrays.
Table of Contents
Here’s an example of how to use std::array in C++:
#include <iostream>
#include <array>
int main() {
// Declare a std::array of integers with size 5
std::array<int, 5> myArray;
// Assign values to the elements of the array
myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
myArray[3] = 40;
myArray[4] = 50;
// Access and print the elements of the array
std::cout << "Array Elements: ";
for (int i = 0; i < myArray.size(); i++) {
std::cout << myArray[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- We include the necessary header files:
<iostream>
for input/output and<array>
for thestd::array
container. - We declare a
std::array
calledmyArray
to store integers. The declaration syntax isstd::array<DataType, Size>
. myArray
is of size 5, meaning it can hold five elements of integer data type.- We assign values to the elements of the array using the array index, just like we do with traditional arrays.
- We use a loop to access and print the elements of the
std::array
. We use thesize()
member function to get the size of thestd::array
, and the loop runs from 0 to 4 (size – 1) using the indexi
. The elements are printed usingstd::cout << myArray[i] << " ";
.
Output:
Array Elements: 10 20 30 40 50
Advantages of using std::array:
- Safety: std::array performs bounds checking to prevent accessing elements outside the valid range. It helps avoid undefined behavior that can occur with raw arrays.
- Type Safety: std::array enforces elements of a consistent data type, ensuring type safety.
- Size Information: std::array provides a size() member function to determine the number of elements in the array, making it easy to iterate over the elements.
- Readability: Using std::array improves code readability compared to raw arrays.
- Support for Standard Algorithms: Since std::array adheres to the standard container requirements, it can be used with standard algorithms like std::sort, std::find, etc.
In summary, std::array is a useful container in C++ that offers the benefits of safety, type-safety, and standard container functionalities for fixed-size arrays.