To my greatest satisfaction, I’ve recently joined a new project. I started to read through the codebase before joining and at that stage, whenever I saw a possibility for a minor improvement, I raised a tiny pull request. One of my pet peeves is rooted in Sean Parent’s 2013 talk at GoingNative, Seasoning C++ where he advocated for no raw loops.When I saw this loop, I started to think about how to replace it:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 #include <iostream> #include <list> #include <string> #include <vector> struct FromData { // ... std::string title; int amount; }; struct Widget { // ... std::list<FromData> data; }; struct ToData { // ... std::string title; int amount; }; struct Response { // ... std::vector<ToData> data; }; Response foo(Widget widget) { std::vector<ToData> transformed_data; for (const auto& element : widget.data) { transformed_data.push_back( {.title = element.title, .amount = element.amount * 42}); } Response response; // ... response.data = transformed_data; return response; } int main() { Widget widget{.data = { {"a", 1}, {"b", 2}, {"c", 1}, }}; auto r = foo(widget); for (const auto& element : r.data) { std::cout << "title: " << element.title << ", amount " << element.amount << '\n'; } } /* title: a, amount 42 title: b, amount 84 title: c, amount 42 */ Please note that the example is simplified and slightly changed so that it compiles on its own.Let’s focus on foo, the rest is there just to make the example compilable.It seems that we could use std::transform. But heck, we use C++20 we have ranges at our hands so let’s go with std::ranges::transform!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 #include <iostream> #include <list> #include <ranges> #include <string> #include <vec...
First seen: 2025-04-19 23:22
Last seen: 2025-04-20 01:22