我有一个 std::vector<boost::optional<double>>
, foo
说。在这个特定的例子中,我需要一个 std::vector<double>
其他 vector 中的任何“可选”元素映射到新 vector 中的 0。
我是否缺少针对此问题的单线解决方案?
另一种选择是不尽如人意
std::vector<double> out(foo.size());
for (auto& it : foo){
out.push_back(it ? *it : 0.0);
}
我欢迎基于 std::optional
的解决方案,即使我还没有使用该标准。
最佳答案
std::transform
解决方案:
std::vector<double> out(foo.size());
std::transform(foo.begin(), foo.end(), out.begin(), [](const auto& opt){ return opt.value_or(0.0); });
编辑:添加了 out
定义。
关于c++ - 将 std::vector<boost::optional<double>> 转换为 std::vector<double>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50096579/