r/cpp • • Dec 15 '21

Modern C++ in Advent of Code

This series, by Šimon Tóth, is a step by step guide through the solutions of Advent of Code 2021 using Modern C++.

242 Upvotes

83 comments sorted by

View all comments

11

u/paul2718 Dec 15 '21

Day one can be reduced (sic) to essentially four lines,

std::vector<int> v;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(v));
std::cout << "pt1 " << std::transform_reduce(v.begin(), v.end() - 1, v.begin() + 1, 0, std::plus<>(), std::less<>()) << "\n";
std::cout << "pt2 " << std::transform_reduce(v.begin(), v.end() - 3, v.begin() + 3, 0, std::plus<>(), std::less<>()) << "\n";

But that's not modern C++, more like C++03 if you replace transform_reduce with inner_product...

6

u/Ayjayz Dec 15 '21

3 lines if you just use the vector's iterator constructor:

auto v = std::vector(std::istream_iterator<int>(std::cin), std::istream_iterator<int>());
std::cout << "pt1 " << std::transform_reduce(v.begin(), v.end() - 1, v.begin() + 1, 0, std::plus<>(), std::less<>()) << "\n";
std::cout << "pt2 " << std::transform_reduce(v.begin(), v.end() - 3, v.begin() + 3, 0, std::plus<>(), std::less<>()) << "\n";

1

u/paul2718 Dec 16 '21

I always miss that. Think we’re still in 1998 (with inner_product as the algorithm) though…

2

u/paul2718 Dec 15 '21

Don’t understand the downvote, seems apropos to show the direct application of a std algorithm and generic functions to this problem. It doesn’t seem to suit ranges as is because of the complications zipping offset views of the range. At least that’s what I found when I tried it.

1

u/TheThiefMaster C++latest fanatic (and game dev) Dec 16 '21

I got a clean solution using range-v3's views::sliding (to be standardised as views::slide in C++23): https://www.reddit.com/r/cpp/comments/rh1g2j/comment/horcny8/?utm_source=reddit&utm_medium=web2x&context=3