两表进行左连接,两表各选择前两列作为键值,使用ranges及c++20,重新生成对应C++代码
#include <ranges>
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<std::pair<int, std::string>> table1{{1, "apple"}, {2, "banana"}, {3, "orange"}, {4, "grape"}};
std::vector<std::pair<int, std::string>> table2{{2, "yellow"}, {3, "orange"}, {5, "red"}, {6, "green"}};
auto left_join = std::views::join(
table1 | std::views::transform([](const auto& pair1) {
return std::views::single(pair1) | std::views::transform([&table2](const auto& pair2) {
return pair2.first == pair1.first ? pair2 : std::pair<int, std::string>{};
});
})
) | std::views::filter([](const auto& p) {
return !p.second.empty();
});
for (const auto& p : left_join) {
std::cout << p.first << "\t" << p.second << std::endl;
}
return 0;
}
注:ranges库需要c++20支持,本代码使用了lambda表达式、容器的初始化列表、auto等语法特性,需要支持对应特性的编译器。
原文地址: https://www.cveoy.top/t/topic/vRJ 著作权归作者所有。请勿转载和采集!