std::array

Fixed-size array container

Interview Relevant: STL container

std::array

A safer, STL-compatible wrapper around C arrays.

Code Examples

std::array as a modern alternative to C arrays.

cpp
1#include <array>
2
3// Declaration
4array<int, 5> arr = {1, 2, 3, 4, 5};
5
6// Access
7arr[0] = 10;
8int val = arr.at(2);  // Bounds-checked
9int first = arr.front();
10int last = arr.back();
11
12// Size (known at compile time)
13constexpr size_t size = arr.size();
14
15// Iterate
16for (const auto& x : arr) {
17    cout << x << " ";
18}
19
20// Fill with value
21arr.fill(0);
22
23// Swap two arrays
24array<int, 5> arr2;
25arr.swap(arr2);
26
27// Works with STL algorithms
28sort(arr.begin(), arr.end());
29auto it = find(arr.begin(), arr.end(), 3);

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In