C++20 Ranges: Left Join Example
Here is an example of left join using ranges in C++20:
#include <iostream>
#include <vector>
#include <ranges>
struct Person {
std::string name;
int age;
};
struct Address {
std::string city;
std::string country;
};
int main() {
std::vector<Person> people = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 35},
{"Dave", 40}
};
std::vector<Address> addresses = {
{"New York", "USA"},
{"London", "UK"},
{"Paris", "France"}
};
auto left_join = people | std::views::join(addresses)
| std::views::filter([](auto p) { return p.age > 30; })
| std::views::transform([](auto p) { return std::make_pair(p.name, p.second.city); });
for (auto [name, city] : left_join) {
std::cout << name << " - " << city << std::endl;
}
return 0;
}
In this example, we have two ranges: 'people' and 'addresses'. We want to perform a left join between these two ranges, so we use the 'join' view to combine them. We then filter the result to only include people who are over 30 years old using the 'filter' view, and finally transform the result into a pair of name and city using the 'transform' view.
The resulting range is then iterated over using a range-based for loop, and each pair of name and city is printed to the console. The output of the program is:
Charlie - Paris
Dave - Paris
原文地址: https://www.cveoy.top/t/topic/lJDb 著作权归作者所有。请勿转载和采集!