Daily bit(e) of C++ | projections in C++20 range algorithms
2 min readMay 22
--
Daily bit(e) of C++ #141, Projection support in C++20 range algorithm variants.
Support for projections is one of the improvements introduced with the C++20 range versions of standard algorithms.
Projections are applied before elements are passed to the corresponding invocable.
Algorithms that operate on multiple source ranges provide a separate projection for each range.
Note that taking an address of standard functions (including members) is undefined behaviour.
#include <ranges>
#include <algorithm>
#include <vector>
struct User {
int64_t id;
std::string name;
};
using namespace std::literals;
std::vector<User> users{{37,"Eliana Green"}, {23, "Logan Sterling"},
{1, "Isla Bennett"}, {7, "Marcel Jones"}};
// Sort users by id (any invocable will work)
std::ranges::sort(users, {}, &User::id);
// {} instantiates the default comparator: std::ranges::less
// std::ranges::sort(users, std::ranges::less{}, &User::id);
// users == {{1,"Isla..."}, {7,"Marcel..."},
// {23,"Logan..."}, {37,"Eliana..."}}
// Find by name
auto it = std::ranges::find(users, "Eliana Green"s, &User::name);
// it->id == 37, it->name == "Eliana Green"
std::vector<int> first{1,2,3,4,5};
std::vector<int> second{1,2,3,4,5};
std::vector<int> out;
std::ranges::transform(first, second, std::back_inserter(out),
[](int left, int right) { return left * right; }, // transformation
[](int left) { return left + 10; }, // projection, first range
[](int right) { return right / 2; }); // projection, second range
// out == 0 (11*0), 12 (12*1), 13 (13*1), 28 (14*2), 30 (15*2)