Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::array

Use case

Fixed-size buffer with bounds checking and STL support.

Explanation

std::array is a fixed-size container that wraps a C array. Unlike raw arrays, it knows its size, works with STL algorithms and has .at() for bound-checked access. T[N] access can be used as well (e.g. for performance critical applications).

Code

#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>

int main() {
  std::array<uint8_t, 4> bytes = {
      // $ echo "stp x29, x30, [sp, #-16]\!" | llvm-mc -triple=aarch64 -show-encoding
      // stp	x29, x30, [sp, #-16]!           // encoding: [0xfd,0x7b,0xbf,0xa9]
      0xFD, 0x7B, 0xBF, 0xA9};

  std::cout << "Size: " << bytes.size() << "\n";
  std::cout << "First: 0x" << std::hex << static_cast<int>(bytes.at(0)) << "\n";
  std::cout << "Last: 0x" << std::hex << static_cast<int>(bytes[3]) << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/std-array
Size: 4
First: 0xfd
Last: 0xa9