Make Grid iterable

This commit is contained in:
2024-09-05 20:10:34 -07:00
parent 9e6223f886
commit d6fc0396cb
11 changed files with 77 additions and 46 deletions

View File

@@ -1,7 +1,6 @@
#ifndef AOCPP_GRID_HPP_
#define AOCPP_GRID_HPP_
#include <concepts>
#include <iostream>
#include <stdexcept>
#include <type_traits>
@@ -12,6 +11,31 @@
namespace aocpp {
struct Grid;
struct GridElement {
const Coord pos;
char elt;
};
class GridIterator {
Grid const& grid_;
std::int64_t x_, y_;
public:
GridIterator(Grid const& grid, std::int64_t x, std::int64_t y)
: grid_{grid}, x_{x}, y_{y} {}
auto operator++() -> GridIterator&;
auto operator*() -> GridElement;
auto operator==(GridIterator const& rhs) const -> bool
{
return x_ == rhs.x_ && y_ == rhs.y_;
}
};
struct Grid {
std::vector<std::string> rows;
std::size_t columns;
@@ -57,28 +81,16 @@ struct Grid {
}
result.rows.emplace_back(std::move(line));
}
} else {
result.columns = 0;
}
return result;
}
/**
* @brief Apply the callback function across all elements of the grid.
*
* @tparam F Type of callback
* @param f Callback function
*/
template <std::invocable<Coord, char> F>
auto each(F f = F{}) const -> void {
auto const h = rows.size();
for (std::size_t y = 0; y < h; y++) {
auto const& row = rows[y];
auto const w = row.size();
for (std::size_t x = 0; x < w; x++) {
f(Coord{static_cast<std::int64_t>(x), static_cast<std::int64_t>(y)}, row[x]);
}
}
auto begin() const -> GridIterator {
return GridIterator{*this, 0, 0};
}
auto end() const -> GridIterator {
return GridIterator{*this, 0, static_cast<std::int64_t>(rows.size())};
}
};