In C++, std::array
is a container that encapsulates fixed size arrays. It is a part of the Standard Template Library (STL) and provides a way to work with arrays in a more convenient and safer way compared to traditional C-style arrays. Here’s how you can construct and use std::array
:
You can initialize a std::array
by specifying its size and type as follows:
#include <array>
#include <iostream>
int main() {
// Initialize a std::array of size 5
std::array numbers = {1, 2, 3, 4, 5};
// Access elements using the array subscript operator
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
Once you have constructed a std::array
, you can use a variety of member functions to interact with it, such as:
at()
- Access an element with bounds checking.front()
- Access the first element.back()
- Access the last element.begin()
and end()
- Provide iterators for the array.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?