c++ - 不同类型的copy_if
问题描述
如果我知道如何提取匹配类型,是否有一种现代方式来表达从不同类型的源容器有条件地复制到目标容器的意图?
将问题作为代码示例更容易:
#include <algorithm>
#include <vector>
struct Foo {};
struct FooBar{
bool is_valid;
Foo foo;
};
std::vector<Foo> get_valid_foos(const std::vector<FooBar>& foobars){
std::vector<Foo> valid_foos;
for(const auto& fbar : foobars){
if(fbar.is_valid)
valid_foos.push_back(fbar.foo);
}
return valid_foos;
}
std::vector<Foo> get_valid_foos_modern(const std::vector<FooBar>& foobars){
std::vector<Foo> valid_foos;
std::copy_if(foobars.begin(), foobars.end(), std::back_inserter(valid_foos),
[](const auto& foobar){
return foobar.is_valid;
});
//?? std::copy requires input and output types to match
return valid_foos;
}
解决方案
使用range-v3:
std::vector<Foo> get_valid_foos(const std::vector<FooBar>& foobars) {
return foobars
| view::filter(&FooBar::is_valid)
| view::transform(&FooBar::foo);
}
这很有表现力。
推荐阅读
- oracle - COM 对象 - 封闭数据集
- php - Laravel:修剪包含的模板
- angular - NgRx:存储模块创建多个实例
- javascript - 屏幕调整大小上的响应式 D3 甜甜圈图
- python - 如何使用python / selenium获取彼此相邻的列表项而不是彼此下方
- javascript - 删除嵌套的 foreach 循环
- mysql - 为什么我的类似查询的处理方式大不相同?
- c - 如何有效地将位掩码的对应值转换为整数?
- javascript - 询问 3d 曲面图时如何修复或解决 plotly 的 event_data("plotly_hover") 中的明显错误
- c# - Gps 跟踪,如何处理具有重叠半径的位置