std::array is a container class that is defined in the <array> header of the C++
Standard Template Library (STL). It is a container that holds a fixed size of
elements of a certain type.
std::array is similar to an ordinary array, but it has some additional features,
such as automatic bounds checking, and it can be passed as a function argument without
the need for explicit pointer arithmetic. It is also a part of STL and thus can be
used with STL algorithms and have the same interface as other STL containers, such
as std::vector or std::list.
One of the main advantages of std::array over a regular C-style array is that it has
better performance. It is implemented as a struct and not a pointer, so it does not
suffer from the same performance penalties as a regular C-style array.
Sure, here's an example of how to use std::array in a more complete way:
Copy code
#include <array>
#include <iostream>
int main() {
// Creating an array with 5 integers and initializing it with default values
std::array<int, 5> arr;
// Accessing an element of the array using the [] operator
arr[3] = 10;
// Iterating over the elements of the array using a range-based for loop
for (const auto& a : arr) {
std::cout << a << ' ';
}
std::cout << std::endl;
// Getting the size of the array
std::cout << "Size of the array: " << arr.size() << std::endl;
// Getting a pointer to the first element of the array
int* p = arr.data();
// Modifying an element of the array using pointer arithmetic
*(p + 2) = 15;
// Iterating over the elements of the array using a pointer
for (int* i = arr.data(); i != arr.data() + arr.size(); ++i) {
std::cout << *i << ' ';
}
std::cout << std::endl;
// Using the fill() function to set all elements to a specific value
arr.fill(20);
for (const auto& a : arr) {
std::cout << a << ' ';
}
return 0;
}
In this example, we create an std::array of 5 integers and initialize it with
default values. We use the [] operator to access an element of the array, and we
use a range-based for loop to iterate over the elements of the array and print
them out. We also use the size() function to get the size of the array and the
data() function to get a pointer to the first element of the array. With the
pointer, we can use pointer arithmetic to modify an element of the array, we also
use a pointer based loop to iterate over the elements of the array.
We also use the fill() function to set all elements to a specific value.
In this way, the std::array is an efficient container that provides automatic
bounds checking and it can be passed as a function argument without the need for
explicit pointer arithmetic which makes it safer to use than a regular C-style
array. It also provides various functions like size(), data() and fill() which
makes it easy to use and write efficient code.
To embed this project on your website, copy the following code and paste it into your website's HTML: