From d47f6f996d8104514447cc56bf60730053a87253 Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Thu, 16 Jan 2025 13:38:14 -0500 Subject: [PATCH] Bring in a row major version of Amit's matrix. --- amt/matrix.hpp | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/amt/matrix.hpp b/amt/matrix.hpp index 73c2eaf..6bd67ab 100644 --- a/amt/matrix.hpp +++ b/amt/matrix.hpp @@ -1,4 +1,5 @@ -#pragma once +#ifndef AMT_MATRIX_HPP +#define AMT_MATRIX_HPP #include #include @@ -82,7 +83,7 @@ namespace amt { } Matrix(std::initializer_list> li) - : m_row(li.size()) + : m_row(li.size()) { for (auto const& row: li) { m_col = std::max(m_col, row.size()); @@ -119,28 +120,28 @@ namespace amt { constexpr const_reverse_iterator rbegin() const noexcept { return std::reverse_iterator(end()); } constexpr const_reverse_iterator rend() const noexcept { return std::reverse_iterator(begin()); } - constexpr auto operator()(size_type r, size_type c) noexcept -> reference { - auto const index = r * m_col + c; // column-major; + constexpr auto operator()(size_type r, size_type c) noexcept -> reference { + auto const index = r + c * m_row; // row-major; assert(index < size() && "Out of bound access"); return m_data[index]; } constexpr auto operator()(size_type r, size_type c) const noexcept -> const_reference { - auto const index = r * m_col + c; // column-major; + auto const index = r + c * m_row; // row-major; assert(index < size() && "Out of bound access"); return m_data[index]; } - constexpr auto operator[](size_type r) noexcept -> View { - auto const base = r * m_col; - assert(r < rows() && "Out of bound access"); - return { .data = m_data + base, .size = m_col }; + constexpr auto operator[](size_type c) noexcept -> View { + auto const base = c * m_row; + assert(c < cols() && "Out of bound access"); + return { .data = m_data + base, .size = m_row }; } - constexpr auto operator[](size_type r) const noexcept -> View { - auto const base = r * m_col; - assert(r < rows() && "Out of bound access"); - return { .data = m_data + base, .size = m_col }; + constexpr auto operator[](size_type c) const noexcept -> View { + auto const base = c * m_row; + assert(c < cols() && "Out of bound access"); + return { .data = m_data + base, .size = m_row }; } friend void swap(Matrix& lhs, Matrix& rhs) noexcept { @@ -158,7 +159,7 @@ namespace amt { } // namespace amt -#if 0 + #include namespace std { template @@ -166,7 +167,7 @@ namespace std { constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } - + auto format(amt::Matrix const& m, auto& ctx) const { std::string s = "[\n"; for (auto r = std::size_t{}; r < m.rows(); ++r) { @@ -174,11 +175,12 @@ namespace std { s += std::format("{}, ", m(r, c)); } s += '\n'; - } + } s += "]"; return format_to(ctx.out(), "{}", s); } }; } // namespace std -#endif + +#endif // AMT_MATRIX_HPP