Make Grid iterable
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
add_library(aocpp src/Startup.cpp src/Coord.cpp src/Parsing.cpp)
|
||||
add_library(aocpp src/Startup.cpp src/Coord.cpp src/Parsing.cpp src/Grid.cpp)
|
||||
target_include_directories(aocpp PUBLIC include)
|
||||
target_link_libraries(aocpp Boost::headers)
|
@@ -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())};
|
||||
}
|
||||
};
|
||||
|
||||
|
19
lib/src/Grid.cpp
Normal file
19
lib/src/Grid.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
#include "aocpp/Grid.hpp"
|
||||
|
||||
namespace aocpp {
|
||||
auto GridIterator::operator*() -> GridElement
|
||||
{
|
||||
return {{x_, y_}, grid_[Coord{x_, y_}]};
|
||||
}
|
||||
|
||||
auto GridIterator::operator++() -> GridIterator &
|
||||
{
|
||||
if (++x_ == grid_.columns)
|
||||
{
|
||||
x_ = 0;
|
||||
y_++;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
} // namespace
|
Reference in New Issue
Block a user