Skip to content

std::array (C++11)

In a Nutshell

A fixed-size array that does not decay into a pointer. It offers the performance of a C-style array while supporting standard container interfaces such as size(), iterators, and assignment.

#include <array>

Core API Quick Reference

OperationSignatureDescription
Element accessreference at(size_type pos)Access element with bounds checking
Element accessreference operator[](size_type pos)Access element without bounds checking
First elementreference front()Access the first element
Last elementreference back()Access the last element
Raw pointerT* data() noexceptDirect access to the underlying array pointer
Fillvoid fill(const T& value)Fill all elements with a specified value
Sizeconstexpr size_type size() noexceptReturns the number of elements (compile-time constant)
Empty checkconstexpr bool empty() noexceptChecks if the array is empty (true if N==0)
Swapvoid swap(array& other)Swaps the contents of two arrays
Begin iteratoriterator begin() noexceptReturns an iterator to the beginning

Minimal Example

cpp
#include <array>
#include <iostream>
// Standard: C++11
int main() {
    std::array<int, 3> arr = {1, 2, 3};
    arr.fill(0);
    arr[0] = 42;
    for (const auto& v : arr)
        std::cout << v << ' '; // 输出: 42 0 0
    std::cout << "\nsize: " << arr.size(); // 输出: size: 3
}

Embedded Applicability: High

  • Zero-overhead abstraction; compiles to code identical to C-style arrays without introducing heap allocation.
  • size() is a compile-time constant, making it suitable for template metaprogramming and static assertions.
  • Supports constexpr, ideal for building lookup tables at compile time.
  • Built-in bounds checking via at() facilitates debugging, and can be removed in Release builds.

Compiler Support

GCCClangMSVC
4.43.119.0

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05