是否有任何标准功能可用于创建具有容器作为 mapped_type 的地图的平面视图?
Is there any standard functionality for creating a flattened view of a map with a container as the mapped_type?
是否有任何标准功能可以在所有对上创建 range/view?以下代码说明了我要创建的视图:
std::unordered_map<std::string, std::vector<int>> m{{"Foo", {1,2}}, {"Hello", {4,5}}};
auto view = ???;
std::vector<std::pair<std::string, int>> v{view.begin(), view.end()};
std::vector<std::pair<std::string, int>> out1{{"Foo", 1}, {"Foo", 2}, {"Hello", 4}, {"Hello", 5}};
std::vector<std::pair<std::string, int>> out2{{"Hello", 4}, {"Hello", 5}, {"Foo", 1}, {"Foo", 2}};
assert(v == out1 || v == out2);
注意:编写一个嵌套的 for 循环来迭代这个结构是微不足道的。
是的,结合 std::ranges::views::join
with std::ranges::views::transform
和一些 lambda。
using namespace std::ranges::views;
auto to_pairs = [](auto & pair){
auto to_pair = [&key=pair.first](auto & value){ return std::pair{ key, value }; };
return pair.second | transform(to_pair);
};
auto view = m | transform(to_pairs) | join | common;
如果C++23最终采用views::cartesian_product
,这里是另一种方式
std::unordered_map<std::string, std::vector<int>> m{
{"Foo", {1,2}}, {"Hello", {4,5}}};
auto view = m | views::transform([](auto& p) {
return views::cartesian_product(views::single(p.first), p.second); })
| views::join;
是否有任何标准功能可以在所有对上创建 range/view?以下代码说明了我要创建的视图:
std::unordered_map<std::string, std::vector<int>> m{{"Foo", {1,2}}, {"Hello", {4,5}}};
auto view = ???;
std::vector<std::pair<std::string, int>> v{view.begin(), view.end()};
std::vector<std::pair<std::string, int>> out1{{"Foo", 1}, {"Foo", 2}, {"Hello", 4}, {"Hello", 5}};
std::vector<std::pair<std::string, int>> out2{{"Hello", 4}, {"Hello", 5}, {"Foo", 1}, {"Foo", 2}};
assert(v == out1 || v == out2);
注意:编写一个嵌套的 for 循环来迭代这个结构是微不足道的。
是的,结合 std::ranges::views::join
with std::ranges::views::transform
和一些 lambda。
using namespace std::ranges::views;
auto to_pairs = [](auto & pair){
auto to_pair = [&key=pair.first](auto & value){ return std::pair{ key, value }; };
return pair.second | transform(to_pair);
};
auto view = m | transform(to_pairs) | join | common;
如果C++23最终采用views::cartesian_product
,这里是另一种方式
std::unordered_map<std::string, std::vector<int>> m{
{"Foo", {1,2}}, {"Hello", {4,5}}};
auto view = m | views::transform([](auto& p) {
return views::cartesian_product(views::single(p.first), p.second); })
| views::join;