Skip to content

std::array (C++11)

In a Nutshell

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

#include <array>

Core API Quick Reference

OperationSignatureDescription
Element accessreference at(size_type pos)Element access with bounds checking
Element accessreference operator[](size_type pos)Element access without bounds checking
First elementreference front()Access the first element
Last elementreference back()Access the last element
Underlying 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() noexceptReturn the number of elements (compile-time constant)
Empty checkconstexpr bool empty() noexceptCheck if the array is empty (true when N==0)
Swapvoid swap(array& other)Swap the contents of two arrays
Begin iteratoriterator begin() noexceptReturn 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

  • A zero-overhead abstraction that compiles down to the exact same code as a C-style array, introducing no heap allocation.
  • size() is a compile-time constant, making it usable in template metaprogramming and static assertions.
  • Supports constexpr, making it ideal for building lookup tables at compile time.
  • The built-in bounds checking of at() simplifies debugging, and it can be removed in Release builds.

Compiler Support

GCCClangMSVC
4.43.119.0

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress