c++ - 将 std::vector<boost::optional<double>> 转换为 std::vector<double>

标签 c++

我有一个 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/

相关文章:

c++ - OpenGL 图像加载 64 位深度

c++ - 如何设置 scons 来构建已生成源文件的项目?

具有默认参数的 C++ 模板

c++ - 在 C++ Builder VCL 中自动化 RegisterClass

c++ - poll返回0但read不阻塞

c++ - 将内联方法从头文件移动到 .cpp 文件

c++ - 如何在 VS Code 中编译 c/c++ 时禁用自动创建 exe 文件?

c++ - 你能从 C++ 调用 CLR 注入(inject)到 SQL Server 中吗?

c++ - 如何阻止在堆栈分配的对象上调用析构函数?

c++ - 为什么 STL 的 std::sort 不适用于不可变类?