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

24

u/wheypoint Ö Dec 15 '21

Great to see c++20 in action and nice write ups

I really like that modern c++ is getting these more functional features but tbh i think they aren't what i'd use here. I Think it's great when some raw loop can be replaced by some more readable desciptive algorithm, even better if it leads to shorter code. But do people really think

uint32_t count_increasing_windows(std::istream &input) {
  auto sliding_window_view = std::ranges::istream_view<uint32_t>(input) 
| std::ranges::views::transform([e1 = 0, e2 = 0, e3 = 0](uint32_t curr) mutable {
    e1 = std::exchange(e2, std::exchange(e3, curr));
    return e1 + e2 + e3;
    });
  return std::ranges::count_if(sliding_window_view, 
                           [prev = std::numeric_limits<uint32_t>::max(), drop = 2]
                           (uint32_t curr) mutable {
                              if (drop > 0) {
                                drop--;
                                return false;
                              }
                              return std::exchange(prev, curr) < curr; });}

is more readable than the equivalent super simple index or iterator based for loop?

Now maybe in haskell you could solve this using a nice functional composition of simple functions but i think it's too much for c++ ranges.

7

u/[deleted] Dec 15 '21

Honestly, it's not. I really pushed it and this solution is actually undefined behaviour since the lambdas are not regular invocable.

But I do think that from a software engineering perspective, moving to ugly functional code will be a good move. Simply because it makes static analysis so much more powerful.

I wish we could write beautiful functional code in C++, but I don't think that will ever happen :-D

25

u/[deleted] Dec 16 '21

It's an unreadable mess. I do not for the life of me understand why people have an issue with seeing a for or while loop. They think it is bad code for some reason which is just bizarre to me. It's far easier to read and shows you *what is actually happening*. It is much better than code compressed into chained, filthy functional bollocks.

-1

u/Troppsi Dec 16 '21

A while and for loop tells you how it's happening, while an algorithm tells you what

3

u/johannes1971 Dec 16 '21

I think I have seen more abuses of std::accumulate as a clever trick to avoid writing a loop, using side effects to achieve the desired goal, than to actually compute a sum.

2

u/dodheim Dec 17 '21

That's not surprising at all – accumulate isn't a poorly-named generalized summation, it's a poorly-named left fold. That said, anyone putting side-effects in their algorithm operations is sorely missing the point and needs to be swatted over the nose with a newspaper a few times.