C++ helper code for Advent of Code, to print most common data structures.
https://godbolt.org/z/WMPvre4vz
#include <iostream>
template<class T> concept IterableConcept =
requires(T&& o) { std::begin(o) != std::end(o); *std::begin(o); };
template<class T> concept StringConcept =
requires(T&& o) { std::string_view{o}; };
template<class T> concept KeyValueConcept =
requires(T&& o) { o.first; o.second; };
template<class T> concept PairConcept =
requires(T&& o) { o.h; o.t; } ||
requires(T&& o) { o.x; o.y; };
struct Osw {
~Osw(){ std::cout << '\n'; }
template<KeyValueConcept T>
const Osw& operator,(const T& o) const {
const auto& [k, v] = o;
return *this, '{', k, ": ", v, '}';
}
template<PairConcept T>
const Osw& operator,(const T& o) const {
const auto& [a, b] = o;
return *this, '(', a, ", ", b, ')';
}
template<IterableConcept T>
requires(!StringConcept<T>)
const Osw& operator,(const T& o) const {
std::cout << '[';
for (int n = 0; auto&& i : o) {
if (n++) std::cout << ", ";
*this, i;
}
std::cout << ']';
return *this;
}
const Osw& operator,(const auto& o) const {
std::cout << o;
return *this;
}
};
#define PRN Osw{},
#include <array>
#include <vector>
#include <unordered_map>
#include <unordered_set>
int main(){
auto il = {1, 2, 3, 4};
PRN "initializer list: ", il;
std::string_view a[][2]{{"sour", "sweet"}, {"cold", "hot"}, {"noise", "music"}};
PRN "array: ", a;
std::array<std::array<const char*, 2>, 3> sa{
{{"red", "blue"}, {"teal", "olive"}, {"green", "black"}}};
PRN "std::array: ", sa;
std::vector v{std::vector{std::unordered_set{2.2}, {3.5}}, {},
{{3.3, 1.2}, {4.4}}, {{5.5}, {6.6}}};
PRN "vector: ", v;
std::unordered_map<int, const char*> m{{1, "one"}, {2, "two"}};
PRN "map: ", m;
struct {std::string h; std::vector<int> t;} o{"head", {3, 2, 1}};
PRN "pair: ", o;
struct {int x, y;} pa[]{{0, 1}, {1, 0}, {1, 1}};
PRN "pair array: ", pa;
}