<array>
The <array>
header, introduced in C++11, provides the std::array
container, which is a fixed-size array that offers the benefits of C-style arrays with additional features of STL containers. It encapsulates a fixed-size array as a template class, providing better type safety and convenience compared to C-style arrays.
std::array<T, N>
: The main container class, where T is the element type and N is the fixed size#include <iostream>
#include <array>
int main() {
std::array<int, 5> numbers = {1, 2, 3, 4, 5};
std::cout << "Size: " << numbers.size() << std::endl;
std::cout << "Element at index 2: " << numbers[2] << std::endl;
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
std::array
#include <iostream>
#include <array>
#include <algorithm>
int main() {
std::array<int, 5> numbers = {5, 2, 4, 1, 3};
std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted array: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
auto max_element = std::max_element(numbers.begin(), numbers.end());
std::cout << "Max element: " << *max_element << std::endl;
return 0;
}
sort
and max_element
std::array
#include <iostream>
#include <array>
#include <stdexcept>
int main() {
std::array<int, 3> arr = {1, 2, 3};
try {
std::cout << arr.at(2) << std::endl; // OK
std::cout << arr.at(3) << std::endl; // Throws out_of_range
} catch (const std::out_of_range& e) {
std::cerr << "Out of Range error: " << e.what() << std::endl;
}
return 0;
}
at()
method for bounds-checked accessstd::array
can throw exceptions for out-of-bounds accessstd::array
is an aggregate type, allowing aggregate initializationstd::get<N>()
std::array
doesn't decay to a pointer when passed to functionsstd::array
can be used with structured bindings in C++17 and laterstd::array
provides a safer and more convenient alternative to C-style arrays in C++. It combines the efficiency of built-in arrays with the benefits of STL containers, such as knowing its own size, supporting iteration, and working seamlessly with STL algorithms.
at()
methodBy using std::array
, C++ developers can write more robust and type-safe code when working with fixed-size arrays, while maintaining the performance characteristics of built-in arrays.
[1] https://en.cppreference.com/w/cpp/container/array [2] https://www.programiz.com/cpp-programming/std-array [3] https://en.cppreference.com/w/cpp/header/array [4] https://stackoverflow.com/questions/26614983/which-headers-in-the-c-standard-library-are-guaranteed-to-include-another-head [5] https://learn.microsoft.com/en-us/cpp/standard-library/array-class-stl?view=msvc-170 [6] https://www.geeksforgeeks.org/stdarray-in-cpp/ [7] https://embeddedartistry.com/blog/2017/06/28/an-introduction-to-stdarray/ [8] https://stackoverflow.com/questions/13131182/c-c-array-variable-in-function-header
Previous Page | Course Schedule | Course Content