core/array2d.hpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <print>
#include <array>
#include <exception>
#include <string>

template<typename T, int SZ1, int SZ2>
requires (SZ1 > 0 && SZ2 > 0)
class Array2D
{
  std::array<T, SZ1 * SZ2> data = {};
public:
  Array2D() = default;
  Array2D(auto... args)
   : data{args...} {   
  }

  // read access for two dimensions:
  const auto& @\TB{operator[]}@ (int x, int y) const {
    if (x < 0 || x >= SZ1) {
      throw std::out_of_range{"invalid row " + std::to_string(x)};
    }
    if (y < 0 || y >= SZ2) {
      throw std::out_of_range{"invalid column " + std::to_string(x)};
    }
    return data[x * SZ2 + y];
  }

  // write access for two dimensions:
  auto& @\TB{operator[]}@ (int x, int y) {
    if (x < 0 || x >= SZ1) {
      throw std::out_of_range{"invalid row " + std::to_string(x)};
    }
    if (y < 0 || y >= SZ2) {
      throw std::out_of_range{"invalid column " + std::to_string(x)};
    }
    return data[x * SZ2 + y];
  }

  void print() const {
    std::println("{}", data);
  }
};