Convert a std::vector<boost::optional<double>> to a std::vector<double>

  • A+

I have a std::vector<boost::optional<double>>, foo say. In this particular instance I need a std::vector<double> where any "optional" element in the other vector maps to a 0 in the new one.

Am I missing a one-line solution for this?

The other choice is the unsatisfactory

std::vector<double> out(foo.size()); for (auto& it : foo){     out.push_back(it ? *it : 0.0); } 

I'd welcome a solution based on std::optional, even though I don't use that standard yet.

std::transform solution:

std::vector<double> out(foo.size()); std::transform(foo.begin(), foo.end(), out.begin(), [](const auto& opt){ return opt.value_or(0.0); }); 

Edit: Added the out definition.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: