C++ STL Sequence Container - Array
In C++, the Standard Template Library (STL) provides several sequence containers, which are data structures that store elements in a linear sequence. One of these containers is the array
container, which provides a fixed-size array with a constant size that is known at compile time.
An array
container can be declared as follows:
#include <array> std::array<int, 5> myArray; // an array of 5 integers
Here, std::array
is a templated class that takes two template parameters: the type of the elements to store (int
in this case), and the size of the array (5
in this case).
The array
container provides several member functions, including:
at()
: returns a reference to the element at a specified position, with bounds checking.operator[]
: returns a reference to the element at a specified position, without bounds checking.front()
: returns a reference to the first element.back()
: returns a reference to the last element.size()
: returns the number of elements in the array.empty()
: returns true if the array is empty.fill()
: fills the array with a specified value.
array
containers can be useful in situations where a fixed number of elements are required, and where the size of the array is known at compile time. They are also more efficient than dynamic arrays, since they do not require dynamic memory allocation and deallocation.
Here is an example of using the array
container:
#include <iostream> #include <array> int main() { std::array<int, 5> myArray = {1, 2, 3, 4, 5}; // Access elements std::cout << "myArray[2] = " << myArray[2] << std::endl; std::cout << "myArray.front() = " << myArray.front() << std::endl; std::cout << "myArray.back() = " << myArray.back() << std::endl; // Fill array with a value myArray.fill(0); // Output array for (int i = 0; i < myArray.size(); ++i) std::cout << myArray[i] << ' '; std::cout << std::endl; return 0; }