C++20 Ranges: Left Join Example
Here's an example of a left join using C++20 ranges:
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
struct Employee {
int id;
std::string name;
int departmentId;
};
struct Department {
int id;
std::string name;
};
int main() {
std::vector<Employee> employees = {
{1, "John", 1},
{2, "Jane", 2},
{3, "Bob", 1},
{4, "Alice", 3},
};
std::vector<Department> departments = {
{1, "Sales"},
{2, "Marketing"},
{3, "IT"},
};
auto joined = employees | std::views::join(departments,
std::ranges::equal_to{},
[](const Employee& e, const Department& d) {
return e.departmentId == d.id;
});
for (const auto& [e, d] : joined) {
std::cout << e.name << " works in " << d.name << "\n";
}
return 0;
}
In this example, we have two ranges: 'employees' and 'departments'. We want to perform a left join on these ranges, where each employee is matched with their department. If an employee doesn't have a department, we still want to include them in the output with a null department.
To perform the left join, we use the 'join' view from the ranges library. The first argument to 'join' is the range we want to join with ('departments'), and the second argument is an equality comparison function ('std::ranges::equal_to{}') that determines how to match elements from the two ranges.
The final argument to 'join' is a lambda function that takes two elements (one from each range) and returns a boolean indicating whether they should be joined. In this case, we join employees with their departments based on their 'departmentId'.
The 'joined' range produced by 'join' contains pairs of matched elements. We use a range-based for loop to iterate over these pairs and print out the employee name and department name. If an employee doesn't have a department, the corresponding department object in the pair will be default-constructed (i.e., with an id of 0 and an empty name).
原文地址: https://www.cveoy.top/t/topic/lJDe 著作权归作者所有。请勿转载和采集!