Is there any convenient way in C++ to convert a vector to a vector other than using transform algorithm and istringstream?
Thanks a lot for your help!
lexical_cast
is quite "convenient".
for(size_t i = 0; i < vec.size(); ++i) {
vec2.push_back(boost::lexical_cast<double>(vec[i]));
}
Of course this becomes even more fun with std::transform
:
std::transform(strings.begin(), strings.end(),
std::back_inserter(doubles),
boost::lexical_cast<double, std::string>); // Note the two template arguments!
atof
could also fit your needs, remember to include cstdlib
:
std::transform(strings.begin(), strings.end(), std::back_inserter(doubles),
[](const std::string& x) { return std::atof(x.c_str()); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With